Question

I have tried to build a Base 10 to Base 2 converter...

  var baseTen = window.prompt("Put a number from Base 10 to convert to base 2");
    var baseTwo = [];
    var num = baseTen;
    var getBinary = function () {
        baseTwo.reverse();
        for (var i = 0; i <= baseTwo.length - 1; i++) {
            document.write(baseTwo[i]);
        }
    };

    var divide = function () {
        while ( num > 0 ) {
            if (num % 2 === 0) {
                baseTwo.push(0);
                num /= 2;
            } else {
                baseTwo.push(1);
                num /= 2;
            }
      }  
        getBinary();
    };

    divide();

I have a problem though...when I run the code it prints endless "1"s :\

I can't seem to find the right condition in the while loop to make it stop at the right time where "num" can't be divided anymore...it needs to stop when reaches zero. But I can't find a way to do it. Help will be appreciated.

Was it helpful?

Solution

At this line(s):

num /= 2;

you´re probably not getting integers. Use Math.floor:

num = Math.floor(num/2);

OTHER TIPS

Clean Recursion method for base10 to base2 Conversion in Javascript

I was doing Hacke-Rank 30 days coding challenge and on 10th Question has this, conversion problem. Here how it goes.

// @author Tarandeep Singh :: Created recursive converter from base 10 to base 2 
// @date : 2017-04-11
// Convert Base 10 to Base 2, We should reverse the output 
// For Example base10to2(10) = "0101" just do res = base10to2(10).split('').reverse().join();
function base10to2(val, res = '') {
  if (val >= 2) {
    res += '' + val % 2;
    return base10to2(val = Math.floor(val / 2), res);
  } else {
    res += '' + 1
    return res;
  }
}

// Well not needed in this case since we just want to count consecutive 1's but still :) 

let n = 13;

var result = base10to2(n).split('').reverse().join();
document.write(`Converting ${n} into Base2 is ${result}`);

On the Side note, you can also use toString method of number to do this.

Like let n = 13; console.log(n.toString(2)); This will also work.

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