给定一个整数(32位有符号整数),写一个方法判断这个数字是否为4的乘方。
样例
样例 1:
输入:num = 16
输出:True
样例 2:
输入:num = 5
输出:False
挑战
你能否不使用循环/递归解决这个问题呢?
解题思路1:
直观思路,循环num=num/4检测num%4是否为0,直到num为1为止。注意,需考虑num为0的情况,否则会陷入死循环,码代码多考虑一些边界特殊情况,再提交!
class Solution {
public:
/**
* @param num: an integer
* @return: whether the integer is a power of 4
*/
bool isPowerOfFour(int num)
{
// Write your code here
if(num == 0)
return false;
while(num != 1)
{
if(num%4 != 0)
return false;
num = num/4;
}
return true;
}
};
解题思路2:
显然挑战让不用循环,我们知道num & (num - 1)可以用来判断一个数是否为2的幂,其中4的幂是2的幂的一个子集,所以对2的幂做一些限制条件,观察到4的幂都是在16进制下的1 4位,那么我们只需与数(0x55555555) <==> 1010101010101010101010101010101,如果得到的数还是其本身,则可以肯定其为4的次方数。
#include<bitset>
class Solution {
public:
/**
* @param num: an integer
* @return: whether the integer is a power of 4
*/
bool isPowerOfFour(int num)
{
// Write your code here
return num>0 && !(num&(num-1)) && (num & 0x55555555)==num;
}
};
java代码:
public class Solution {
/**
* @param num: an integer
* @return: whether the integer is a power of 4
*/
public boolean isPowerOfFour(int num) {
// Write your code here
return num > 0 && (num&(num-1)) == 0 && ((num&0x55555555)==num);
}
}