0

Okay I know there is already a lot of solutions for this title. I have gone through those links but didn't help

I am new to java and I am writing one simple decimal to binary conversion program. In which a user will input the decimal number base 10 and get the output in binary form base 2.

I have already written a program but I am not getting the proper output. Something is missing which I am unable to identify.
Here is my code

import java.util.Scanner;
class BinaryConversion{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the decimal number to convert into binary");
        int num = scan.nextInt();
        StringBuilder BinaryString = new StringBuilder();
        BinaryString.setLength(0);
        while(num!=1){
            num/=2;
            int r = num%2;
            BinaryString.append(Integer.toString(r));
        }
        System.out.println(BinaryString.reverse());
    }
}


In the above program If I enter the decimal number let's say 95 the output should be 1011111.
But I am getting 101111
Please help.

1 Answers1

1

You are stopping when num equals 1. And doing the division at first would miss one binary digit.

while(num!=1){
    num/=2;
    int r = num%2;
    BinaryString.append(Integer.toString(r));
}

would be:

while (num > 0) { // till the remaining is greater than zero        
    int r = num % 2; // at first fetching the modulus result
    BinaryString.append(Integer.toString(r));
    num /= 2; // then dividing
}
Shahid
  • 2,288
  • 1
  • 14
  • 24