[LeetCode] Power of Four

Posted immjc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode] 342. Power of Four

[LeetCode] Power of Four

342. Power of Four(LeetCode)

LeetCode 342. Power of Four

leetcode 342. Power of Four

[leetcode-342-Power of Four]