C++ one line use bit manipulation with explanation


  • 3
    D
    bool isPowerOfFour(int num) {
          return num > 0 && (num&(num-1))==0 && (num&(0xAAAAAAAA))==0;
    }
    
    (num & (num-1)) == 0  mean num is power of two
    (num & (0xAAAAAAAA)) == 0 mean num in binary do not have even bit 1, something like 1010
     combine those, the num is power of four.

Log in to reply
 

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