HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptMinor

JavaScript function to convert decimal number to binary

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numberjavascriptconvertdecimalfunctionbinary

Problem

I was recently asked this in an interview for a front-end position and I came up with something like the code below, which seems to work but is clunky. (Number.toString() was not allowed.)

function convertBinary(number) {
  var n = 0;
  var binaryArr = [];

  var difference = Math.pow(2, n);

  //find out how many digits are needed
  while (difference  0) {
    if (Math.pow(2, n) <= number) {
      binaryArr[n] = 1;
      number-= Math.pow(2, n);
    }
    n--;
  }

  return binaryArr.reverse().join("") * 1
}


Also I was asked what the Big(o) of this was but had a hard time figuring it out— what is the time complexity of JavaScript reverse?

Solution

Strictly speaking, the number parameter isn't decimal; it's just an abstract number. (This is more a criticism of the terminology in your question title than of your code.) On the other hand, it is very weird that you coerce the result into a number (101010) rather than returning it as a string ('101010').

The implementation strategy, using Math.pow(…, 2), strikes me as extravagant. You should be able to do this more efficiently using just arithmetic:

function convertBinary(number) {
    var binaryArr = [];
    for (; number; number /= 2) {
        binaryArr.push(number % 2);
    }
    return binaryArr.reverse().join('');
}


… or the same thing using bitwise operations:

function convertBinary(number) {
    var binaryArr = [];
    for (; number; number >>= 1) {
        binaryArr.push(number & 1);
    }
    return binaryArr.reverse().join('');
}

Code Snippets

function convertBinary(number) {
    var binaryArr = [];
    for (; number; number /= 2) {
        binaryArr.push(number % 2);
    }
    return binaryArr.reverse().join('');
}
function convertBinary(number) {
    var binaryArr = [];
    for (; number; number >>= 1) {
        binaryArr.push(number & 1);
    }
    return binaryArr.reverse().join('');
}

Context

StackExchange Code Review Q#121944, answer score: 5

Revisions (0)

No revisions yet.