Question

I have created a converter which will hopefully convert any normal number which is inputted into a binary number, but it will only return the number "1" no matter what you input, why?

import java.util.Scanner;
public class NumtoBinary{
public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    System.out.println("Welcome to the Number to binary converter");
    int Num = sc.nextInt();
    System.out.println(toBin(2));
}
    public static int toBin(int Num){
        int result = 0;

        while(Num > 0){
            int mod = Num % 2;
            result = result * 1 + mod;
            Num /= 2;
        }
        return result;
    }

}

Was it helpful?

Solution

Your approach is close but for each iteration that produces zero for the mod you need to reflect that. You could use a String to track the result of each iteration and convert it to an integer for the return value like this:

public static int toBin(int Num) {
   String result = "";

   while (Num > 0) {
      int mod = Num % 2;
      result = mod + result;
      Num /= 2;
   }
   return Integer.parseInt(result);
}

For example the method above if you input 12 then each iteration would build the string like this "0", "00", "100", "1100"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top