[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);
    }
原文地址:https://www.cnblogs.com/hellowooorld/p/7707300.html