Convert int to binary base 2 10 base 2 = 1010, 3 base 2 = 11
If we want to convert a number to a binary base 2, we let the number mod 2, if the mod number is 0, we insert 0 in the first position, if the mod number is 1, we inser 1 in the first position.
public String convertBase2(int number) {
if (number==0) {
return "0";
}
StringBuilder sb = new StringBuilder();
while (number!=0) {
int temp = number % 2;
if (temp==0) {
sb.insert(0, 0);
} else {
sb.insert(0, 1);
}
number = number / 2;
}
return sb.toString();
}
Convert int to binary base (x), where x is a parameter
解法类似,给出一个所有可能的数字组合。
public String convert(int number, int base) {
if (number==0) {
return "0";
}
String digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
StringBuilder sb = new StringBuilder();
while (number!=0) {
int temp = number % base;
sb.insert(0, digits.charAt(temp));
number = number / base;
}
return sb.toString();
}