1 递归
public static void decimalToBinaryByRecursion(int decimal,StringBuilder binary){
if(decimal <= 0){
return;
}
decimalToBinaryByRecursion(decimal/2,binary);
binary.append(decimal % 2);
}
2 循环
public static String decimalToBinaryByCirculate(int decimal){
String binary="";
while (decimal > 0){
int temp=decimal%2;
binary=temp+binary;
decimal=decimal/2;
}
return binary;
}
3 位运算
public static String decimalToBinaryByBitwise(int decimal){
StringBuilder binary = new StringBuilder();
while (decimal > 0) {
binary.append(decimal & 1);
decimal >>>= 1;
}
return binary.reverse().toString();
}
4 测试程序
public static void main(String[] args) {
int decimalData=25;
StringBuilder binary=new StringBuilder();
decimalToBinaryByRecursion(decimalData,binary);
System.out.print("递归:");
System.out.println(binary);
System.out.print("循环:");
System.out.println(decimalToBinaryByCirculate(decimalData));
System.out.print("位运算:");
System.out.println(decimalToBinaryByBitwise(decimalData));
}
5 运行结果