C one line bit manipulation solution with explanation


  • 3
    bool isPowerOfFour(int num) {
        return (!(num & (-num) ^ num)) && (num & 0x55555555);
    }
    
    • num & (-num) will get the last non-zero bit;
    • ^ num will flip num with that bit, if num is power of 2, (num) & (-num) ^ num should be 0;
    • num & 0x55555555 will further make sure that num is power of 4, because 0x55555555 is 0b01010101010101010101010101010101 in binary.

Log in to reply
 

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