JavaScript 3 lines solution


  • 0

    To flip the number, we should

    1. Get the complement of the 32-bit positive(which means unsigned) number
        var com = ~num >>> 0;
    
    1. Find out how many bits you should keep
        var len = num.toString(2).length;
    
    1. Left shift 32-len bits to remove all the 1, and move back the result bits
        return ((com << (32-len)) >>> (32-len));
    

    Note that >>> means shift the number without sign bit so we won't get negative result

    ex: input = 5 (101)

    1. com = 11111111 11111111 11111111 11111010
    2. len = 3
    3. com << 27 = 010 000...... com >>> 27 = 00000000 00000000 00000000 00000010

Log in to reply
 

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