342. Power of Four

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example: Given num = 16, return true. Given num = 5, return false.

Follow up: Could you solve it without loops/recursion?

class Solution {
public:
    bool isPowerOfFour(int num) {
        switch(num){
            case 1:
            case 4:
            case 16:
            case 64:
            case 256:
            case 1024:
            case 4096:
            case 16384:
            case 65536:
            case 262144:
            case 1048576:
            case 4194304:
            case 16777216:
            case 67108864:
            case 268435456:
            case 1073741824:
                return true;
            default: 
                return false;
        }
    }
};

Or

class Solution {
public:
    bool isPowerOfFour(int num) { 
        return (num < 1 ? false : (num | (num-1)) == num * 2 - 1)  // power of 2, only one 1 in 4 byte
               && (num & 0xaaaaaaaa) == 0;  // power of 4: 0101 0101 0101 0101,
    }
};

你可能感兴趣的:(342. Power of Four)