public static void integerToBinary(Integer number){
//使用num%2得到商和余数
//使用上一步的商%2
//直到商为o, 将这些余数到倒过来就是二进制
int remainder = 0; //余数
int quotient = 0; //商
StringBuilder s = new StringBuilder();
while(number > 0){
remainder = number % 2;
quotient = number / 2;
s.append(Integer.toString(remainder));
number = quotient;
}
System.out.println(s.reverse().toString()); //将字符串倒过来
}
public static void integerToBinaryUseStack(Integer number){
//使用num%2得到商和余数
//使用上一步的商%2
//直到商为o
int remainder = 0; //余数
int quotient = 0; //商
Stack<Integer> stack = new Stack<Integer>();
while(number > 0){
remainder = number % 2;
quotient = number / 2;
stack.push(remainder);
number = quotient;
}
while (!stack.empty()){
System.out.print(stack.pop()); //哈哈, 使用队列后进先出的特点
}
}
测试代码
public static void main(String[] args) {
//6的2进制数为110
// System.out.println(6%2); //3 0
// System.out.println(3/2); //1 1
// System.out.println(1%2); //0 1
integerToBinary(6); //110
integerToBinaryUseStack(6); //110
}
来源:https://blog.csdn.net/csdnLeraner/article/details/100165901