Search code examples
javascriptwhile-looptime-complexityspace-complexity

Looking for time and space effective algorithm to convert any integer number into binary value


I am totally a newbie to programming and this is my first question posted in an online community . I have written a function using JavaScript to convert any integer number into binary value.

function number2Binary(inputNumber){
var digitsArray=[];
if(inputNumber === 0 || inputNumber === 1)
{
  return inputNumber;
}
while(inputNumber>0){
  var bit = inputNumber%2;
  inputNumber= parseInt(inputNumber/2);
  digitsArray.push(bit);
}
return digitsArray.reverse().join(" ");  
}
number2Binary(2);

I am pretty sure this may not be an optimal solution. Can someone please suggests a better solution for this problem? Additional question: 1. I used a while loop in my script. How to calculate time complexity for a while loop?


Solution

  • Since everything is an Object in JavaScript, numbers are objects too, and because of this you can invoke methods on them.

    For numbers there is Number.prototype.toString that takes one argument, the base.

    If you have your value inside the inputNumber variable, then you can call inputNumber.toString(2).

    You can also do the same with hardcoded values: 1.1.toString(2).

    Be careful if you want to print constant integer because the first dot will be parsed as the decimal point, so you have to write (1).toString(2) or 1.0.toString(2) or just 1..toString(2) in order to display an hardcoded number.