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?

答案:

判断一个数是否是4的幂,不能使用循环和递归:

     前面我们已经做过一个数是否为2的幂这道题,4的幂跟2的幂一样,都是最高位为1,其他位为0。

     不同的是4的幂中的1在偶数位上,所以我们可以用0xaaaaaaaa与之按位与。

1 class Solution {
2 public:
3     bool isPowerOfFour(int num) {
4         return num>0&&(!(num&(num-1)))&&(!(num&(0xaaaaaaaa)));
5     }
6 };
原文地址:https://www.cnblogs.com/Reindeer/p/5639100.html