Java中将十进制转换为二进制

时间:2020-02-23 14:34:00  来源:igfitidea点击:

在本教程中,我们将看到如何在Java中将十进制转换为二进制。

在java.let中,有很多方法可以将十进制转换为java.let逐个探索它们。

使用Integer.tobinerstring()方法

我们可以简单地使用内置的Integer.tobinerstring()方法来转换十进制

package org.arpit.theitroad;
 
public class DecimalToBinaryInBuiltMain {
 
	public static void main(String[] args) {
 
		System.out.println("Binary representation of 12 : "+ Integer.toBinaryString(12));
		System.out.println("Binary representation of 32 : "+Integer.toBinaryString(32));
		System.out.println("Binary representation of 95 : "+Integer.toBinaryString(95));
	}
 
}

使用迭代阵列方法

package org.arpit.theitroad;
import java.util.Scanner;
public class DecimalToBinaryArrayMain
{
	public static void main(String arg[])
	{
 
		Scanner sc=new Scanner(System.in);
		System.out.println("Enter a decimal number");
		int n=sc.nextInt();
		int binary[]=new int[100];
		int index = 0;
		while(n > 0)
		{
			binary[index++] = n%2;
			n = n/2;
		}
		System.out.print("Binary representation is : ");
		for(int k = index-1;k >= 0;k--)
		{
			System.out.print(binary[k]);
		}
 
		sc.close();
	}
}

使用堆栈

package org.arpit.theitroad;
	
	import java.util.Scanner;
	import java.util.Stack;
	
	public class DecimalToBinaryStackMain
	{
		public static void main(String[] arg) 
		{ 
			Scanner scanner= new Scanner(System.in); 
			Stack<Integer> stack= new Stack<Integer>(); 
			System.out.println("Enter decimal number: ");  
			int num = scanner.nextInt();
			while(num != 0)
			{
				int d = num % 2;
				stack.push(d);
				num /= 2;
			} 
			System.out.print("Binary representation is : ");
			//Print binary presentation
			while (!(stack.isEmpty() ))
			{
				System.out.print(stack.pop());
			}
			scanner.close();
		}
	}