c++ bitset solution 3ms


  • 2
    3
    bool isPowerOfFour(int num) {
        if(num <= 0){
            return false;
        }
        
        bitset<32> n(num);
        if(n.count() != 1){
            return false;
        }
        for(int i = 0; i < 32; i++){
            if(n[i] == 1 && i % 2 == 0){
                return true;
            }
        }
        return false;
    }
    

    If it's power of two, it will only contain one "1" like ( 0001, 0010, 0100 so on);
    if it's power of four, it will only contain one "1" AND the "1" must be at even position.


Log in to reply
 

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