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?
我的做法:
class Solution {
public:
bool isPowerOfFour(int num) {
float num2=num;
while (num2>1)
{
num2=num2 /4;
}
if (num2 == 1)
return true;
else
return false;
}
};
但是太冗余了,别人的做法用到num&(num-1)判断二进制里有几个1,而且也可以用与0x55555555的方法。
public class Solution {
public boolean isPowerOfFour(int num) {
return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0x55555555) == num);
}
}