首页 > 代码库 > [LeetCode] Power of Four

[LeetCode] 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?

判断一个数是否是4的幂,如果一个数是4的幂,则这个数的二进制的1在偶数位上。所以先判断一个数是不是2的幂。然后判断这个数与0x55555555按位与的结果,0x55555555使用十六位表示的数,它的奇数位上全是1,偶数位上全是0。

class Solution {
public:
    bool isPowerOfFour(int num) {
        if (num <= 0)
            return false;
        if (!(num & (num - 1)))
            if (num & 0x55555555)
                return true;
        return false;
    }
};
// 3 ms

相关题目:Power of Two

相关题目:Power of Three

[LeetCode] Power of Four