題目(北大)
將一個(gè)長(zhǎng)度最多為30位數(shù)字的十進(jìn)制非負(fù)整數(shù)轉(zhuǎn)換為二進(jìn)制數(shù)輸出。
做法
使用 java 的 BigInteger類
代碼
import java.math.BigInteger;
import java.util.Scanner;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
String s1 = new String();
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()) {
s1 = scanner.nextLine(); // 輸入一個(gè)十進(jìn)制數(shù)
// System.out.println(s1);
BigInteger b1 = new BigInteger(s1);
BigInteger b2 = new BigInteger("2");
BigInteger zero = new BigInteger("0");
Vector<BigInteger> v = new Vector<BigInteger>(); // 十進(jìn)制轉(zhuǎn)換為二進(jìn)制數(shù)
BigInteger[] arr = b1.divideAndRemainder(b2);
v.add(arr[1]); // 存儲(chǔ)余數(shù)
BigInteger div = arr[0];
while(!arr[0].equals(zero)) {
arr = div.divideAndRemainder(b2);
// System.out.println(arr[0] + " " + arr[1]);
v.add(arr[1]);
div = div.divide(b2);
}
// v 中存儲(chǔ)的即為逆序的二進(jìn)制數(shù)
// 將二進(jìn)制數(shù)轉(zhuǎn)換為十進(jìn)制數(shù)
for(int i = v.size()-1; i >= 0; i--) {
System.out.print(v.get(i));
}
System.out.println("");
}
scanner.close();
}
}