JavaScript solutions, bits and strings


  • 0

    The bit version:

    var findComplement = function(num) {
        let mask = 1;
        while (mask < num) mask = (mask << 1) | 1;
        return num ^ mask;
    };
    

    The string version:

    var findComplement = function(num) {
        return parseInt(num.toString(2).split('').map(d => +!+d).join(''), 2);
    };
    

    A combination of bits and strings that is fast:

    var findComplement = function(num) {
        return parseInt((~num ^ 1 << 31).toString(2).substr(-num.toString(2).length), 2);
    };
    

    In the last solution we negate the bits, including leading zeros, and get rid of the sign bit. Then we take the right side that we need which has the same number of digits as num.


  • 0
    F

    Nice. I m guessing +!+ somehow does some sort of type conversion which avoids having to do what I did here...

    parseInt(num.toString(2).split('').map(function(char) {
        return (parseInt(char, 10)) ? '0' : '1';
    })
    .join(''), 2)
    

  • 0

    @figuer25 indeed! + used as a unary operator (single operand) converts d, the string '0' or '1', to its number form which is falsy or truthy respectively, so we can boolean negate and convert it back in the same fashion by applying ! followed by +.


Log in to reply
 

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