Java decimal to binary using toBinaryString and stack

Hey guys!! Welcome to flower brackets blog. In this post we are going to learn java decimal to binary using toBinaryString and stack.

Java decimal to binary using toBinaryString and stack

Here are ways to convert decimal to binary,

Also read – decimal to binary logic

Using toBinaryString() method

public class DecimalToBinary
{
public static void main(String[] args)
{
System.out.println("Decimal to binary of 104 : ");
System.out.println(Integer.toBinaryString(104));
System.out.println("\nDecimal to binary of 554 : ");
System.out.println(Integer.toBinaryString(554));
System.out.println("\nDecimal to binary of 644 : ");
System.out.println(Integer.toBinaryString(644));
}
}

Output:

Decimal to binary of 104 : 1101000

Decimal to binary of 554 : 1000101010

Decimal to binary of 644 : 1010000100

Using stack

import java.util.*;

public class DecimalBinaryExample
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Stack numStack = new Stack();
System.out.println("Please enter a decimal number : ");
int number = sc.nextInt();
      while(number != 0)
{
int a = number % 2;
numStack.push(a);
number /= 2;
}
System.out.print("Binary number : ");
while(!(numStack.isEmpty()))
{
System.out.print(numStack.pop());
}
System.out.println();
sc.close();
}
}

Output:

Please enter a decimal number : 665
Binary number : 1010011001

Related Posts