[leetcode-342-Power of Four]

Posted hellowOOOrld

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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.

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

思路:

首先是2的幂,然后二进制表示类似于40 = 1,41=100,42=10000。1总是出现在奇数位置上,所以可以用num & 0x55555555==num来判断。

 bool isPowerOfFour(int num) {
        return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0x55555555) == num);
    }

 


以上是关于[leetcode-342-Power of Four]的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 342. Power of Four

leetcode 342. Power of Four

[leetcode-342-Power of Four]

LeetCode 342 Power of Four

[LeetCode] 342. Power of Four(位操作)

LeetCode 342. Power of Four (4的次方)