JavaScript bit operation


  • 0
    F

    Let's say the input is 5, which binary representation is 101.
    We want to flip every bit, so we want a XOR operation (a & b) between it and 111.

    Now how do we get this full-1 number? My approach is to get the number of digits of the binary representation by using Math.log2, and then calculating 2 power of this range minus one to get all ones.

    var findComplement = function(num) {
        if (num === 0) { return 1; }
        return num ^ (Math.pow(2, Math.floor(Math.log2(num))+1)-1);
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.