Search code examples
javabinarylogicdecimal

Issues Converting to Binary While Using a While Loop


I'm currently trying to solve the binary gap problem in java and started off with first trying to convert the decimal into binary using a while loop. I was testing it with different decimal inputs, but noticed after stepping through it, that on the final loop I'm getting integer overflow instead of appending a 1, (or at least I think I am, it goes from 100010000 to 411065418, I'm assuming because it multiples the 100010000 *10)

I tried stepping through it and This is my code currently:

public class BinaryGap {
     public static void main(String[] args) {
        // write your code in Java SE 8
        int decimal = 529;
        int ans =0; 
        //returns the number in binary but in big endian form
        while(decimal != 0){
            ans += (decimal % 2);
            ans *= 10; 
            decimal /=2;             
          }
    }
}

Any help in telling me where my line of thinking is wrong would be greatly appreciated


Solution

  • Your code is conceptually working fine - but variable 'ans' meets the limit of int - 2147483647.
    When +1 is added to this value - variable overflows and goes to minimal value.
    To overcome it you can use type 'String' for 'ans' variable with small adjustments to code:

    int decimal = 529;
    String ans = "";
    //returns the number in binary but in big endian form
    while(decimal != 0){
        ans += (decimal % 2);
        decimal /=2;
    }