将十进制数转换为二进制数有以下三种方法:
1)使用Integer类的toBinaryString()方法。
2)通过编写自己的逻辑进行转换,而无需使用任何预定义的方法。
3)使用Stack
方法 1:使用toBinaryString()方法
class DecimalBinaryExample{ public static void main(String a[]){ System.out.println("Binary representation of 124: "); System.out.println(Integer.toBinaryString(124)); System.out.println("\nBinary representation of 45: "); System.out.println(Integer.toBinaryString(45)); System.out.println("\nBinary representation of 999: "); System.out.println(Integer.toBinaryString(999)); }}输出:
Binary representation of 124: 1111100Binary representation of 45: 101101Binary representation of 999: 1111100111
方法 2:不使用预定义的方法
class DecimalBinaryExample{ public void convertBinary(int num){ int binary[] = new int[40]; int index = 0; while(num > 0){ binary[index++] = num%2; num = num/2; } for(int i = index-1;i >= 0;i--){ System.out.print(binary[i]); } } public static void main(String a[]){ DecimalBinaryExample obj = new DecimalBinaryExample(); System.out.println("Binary representation of 124: "); obj.convertBinary(124); System.out.println("\nBinary representation of 45: "); obj.convertBinary(45); System.out.println("\nBinary representation of 999: "); obj.convertBinary(999); }}输出:
Binary representation of 124: 1111100Binary representation of 45: 101101Binary representation of 999: 1111100111
方法 3:使用Stack进行二进制到十进制转换
import java.util.*;class DecimalBinaryStack{ public static void main(String[] args) { Scanner in = new Scanner(System.in); // Create Stack object Stack<Integer> stack = new Stack<Integer>(); // User input System.out.println("Enter decimal number: "); int num = in.nextInt(); while (num != 0) { int d = num % 2; stack.push(d); num /= 2; } System.out.print("\nBinary representation is:"); while (!(stack.isEmpty() )) { System.out.print(stack.pop()); } System.out.println(); }}
输出:
Enter decimal number: 999Binary representation is:1111100111
