leetcode : 190. Reverse Bits JavaScript solution

Posted on

Here is a simple way to reverse bits in JavaScript. This method uses string manipulation rather than bit manipulation, but it works and may be easier to grasp for someone who does not have a Computer Science background.

toString(2)

This is one of the keys to making the solution work. The input is a base 10 number. When calling toString() on the number we can also apply an optional parameter radix, which is a fancy way of saying “base”, and in this case base 2 aka binary.

var reverseBits = function(n) {
    //convert the number to base2 then stringify, split, and reverse 
    let reversedArray = n.toString(2).split("").reverse()
    //the converted number may not be 32 digits so pad the end 
    while(reversedArray.length <32){ reversedArray.push('0')}
    //join the string, then convert to Integer from base 2
    return  parseInt(reversedArray.join(""),2) 
};
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s