Home > Back-end >  Convert Decimal Number to Binary without using Array
Convert Decimal Number to Binary without using Array

Time:03-22

I want to make a java code that converts any decimal number inputted, into binary number. Although the array method is easy, it doesn't actually prints a number(it prints array), nor does it seem to correctly use the algorithm we use manually. So I'm trying to do it without array. The problem is it sometimes giving correct answers, and sometimes giving wrong answers. I think the problem might be in multiplying by zero in the last cycle of loop, but I'm not sure. The code I wrote as comment was a failed try to resolve the issue.

import java.util.Scanner;

public class DecToBin {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long dec = 0, num = 0, rem = 0;
        
        System.out.print("Enter A Decimal Number: ");
        dec = sc.nextLong();
        while(dec > 0){
            rem = dec % 2;
            num  = rem;
            num *= 10;
            dec /= 2;

        }
        // if(num % 100 == 10){
        //     num = num/10;
        // }
        System.out.println("Binary Equivalent: "   num);


    }
}
 

CodePudding user response:

This problem lends its self to a recursive solution

  private static int DecToBin(final int input, final int result) {
    if (input == 0) {
      return result;
    }
    return DecToBin(input / 2, result * 10   input % 2);
  }

CodePudding user response:

I found following "direct" issues with your code:

  1. You are not reversing the final number. In the manual way of converting DEC->BIN, we reverse the final representation. Hint: Dry run for input 11
  2. You are doing num = rem; num *= 10. The order is wrong. You should be multiplying it before you add the remainder. eg. Your code will output 1010 for 5, instead of 101.
  3. By your method, you are trying to represent decimal number into its binary representation as int, which limits your input to 2047, as 2048 and above need 11 digits for their binary representation and you can't have that in int. You should use String if you don't want to use array. Also, reversing would be easier.

something like:

import java.util.Scanner;

public class DecToBin {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int dec = 0, num = 0;
        
        System.out.print("Enter A Decimal Number: ");
        dec = sc.nextInt();
        String bi = "";
        while(dec > 0){
            int rem = dec % 2;
            // num *= 10;
            // num  = rem;
            bi  = Character.toString(rem   48);
            dec /= 2;

        }
        // if(num % 100 == 10){
        //     num = num/10;
        // }
        System.out.println("Binary Equivalent: "   new StringBuilder(bi).reverse().toString());


    }
}
  • Related