Convert to Binary

May 04, 2018

Question:

Given a non-negative integer n, write a function toBinary/ToBinary which returns that number in a binary format.

 

Solutions:

A(General Solution)

function toBinary(n){
    var r = [], rem;
    while(n>0) {
        rem = Math.floor(n % 2);
        r.push(rem);
        n = Math.floor(n/2);
    }
    n = r.reverse().join('');
    return n;
}

B(JS Solution)

function toBinary(n){
    var s = n.toString(2);
    var n = Number(s);
    return n;
}

This question is referred from Codewars