KY-30进制转换
(java实现)
题目描述:
将一个长度最多为30位数字的十进制非负整数转换为二进制数输出。
输入描述:
多组数据,每行为一个长度不超过30位的十进制非负整数。 (注意是10进制数字的个数可能有30个,而非30bits的整数)
输出描述:
每行输出对应的二进制数。
示例1:
输入
0 1 3 8
输出
0 1 11 1000
问题分析:
本题难点在于十进制数的位数大于30位;
思路一:直接调用java内置函数,保证按整数读取到的。(BigInteger)
思路二:使用数***算的原来处理,即竖式运算。
相关知识:
使用大整数的头文件以及相关函数:
import java.math.*;
BigInteger num = new BigInteger(line,10);
System.out.println(num.toString(2));
参考代码:
思路一实现:
import java.util.*; import java.math.*; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { String line = input.nextLine(); BigInteger num = new BigInteger(line,10); System.out.println(num.toString(2)); } } }
思路二实现:
import java.util.*; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); //char[] str = new char[31]; while (input.hasNext()) { //int a = input.nextInt(); String line = input.nextLine(); char[] str = line.toCharArray(); int size = str.length; int[] num = new int[31]; int[] res = new int[2000]; //字符串转数字 for (int i=0; i<size; i++) { num[i] = str[i]-'0'; } int index = 0; for (int i=0; i<size; ) { int tmp=0,remain=0; for (int j=i; j<size; j++) { tmp = (10*remain+num[j])%2; num[j] = (10*remain+num[j])/2; remain = tmp; } res[index] = remain; index++; //while (0 == num[i]) //i<size避免越界 while (0==num[i] && i<size) { i++; } } for (int i=index-1; i>=0; i--) { System.out.print(res[i]); } System.out.println(); } } }
其他
#include<stdio.h> #include<stdlib.h> #include<string.h> #define LEN 2000 char str[LEN],another[LEN]; int ten[LEN]; int switchToTen(int m); void switchToAnother(int k, int n); int main() { int m, n, k; while (scanf("%d %d",&m, &n) != EOF) { scanf("%s", str); k = switchToTen(m); switchToAnother(k, n); } //system("pause"); return 0; } int switchToTen(int m) { int i, j, len, k, c; //初始化 len =strlen(str); k=1; memset(ten, 0, sizeof(ten)); //转换为十进制 for (i = 0; i < len; i++) { for (j = 0; j < k; j++) { ten[j] *= m; } if (str[i] >= '0' && str[i] <= '9') { ten[0] += str[i] - '0'; }else if (str[i] >= 'A' && str[i] <= 'Z') { ten[0] += str[i] - 'A' + 10; }else if (str[i] >= 'a' && str[i] <= 'z') { ten[0] += str[i] - 'a' +10; } for (j= c = 0; j < k; j++) { ten[j] +=c; if (ten[j] >= 10) { c = ten[j] /10; ten[j] %= 10; }else { c = 0; } } while (c) { ten[k++] = c % 10; c = c / 10; } } //翻转数组 int temp; for (i = 0, j= k - 1; i < j; i++, j--) { temp = ten[i]; ten[i] = ten[j]; ten[j] = temp; } return k; } void switchToAnother(int k, int n) { int sum, r, t, d; sum = 1; r = 0; memset(another, 0, sizeof(another)); while (sum) { sum = 0; for (int i = 0; i < k; i++) { d = ten[i] / n; sum += d; if (i == k-1) { t = ten[i] % n; if (t >= 0 && t <= 9) { another[r] = t + '0'; }else { another[r] = t - 10 + 'a'; } r++; }else { ten[i+1] += ten[i] %n*10; } ten[i] = d; } } //打印输出 for (int i = r-1; i >= 0; i--) { printf("%c", another[i]); } printf("\n"); }