LeetCode 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.

Nothing special here.

num & (num - 1) means only there is one 1 in the bit representation.

Think that if it is a pow of 4. there must be even number of zeros before 1. for example: 0000....1 / 00000..100 ... /0000.. 01010101  -> 0x55555555

    bool isPowerOfFour(int num) {
        if(num <= 0) return false;
        if ( (num & (num-1)) == 0 && (num & 0x55555555) != 0 )
            return true;

        return false;
    }



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