Task:
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?
Some Questions:
Can I use the log function?
Solution:
Obviously, we can use loop to check whether the given number is equal to 4,4^2,4^3,..,4^15.
But how to solve it without loops? In fact, we have solve the problem power of 2. It calculates whether the given number is a divisor of (1<<30).
So, this problem can we solve it by checking whether the given number is a divisor of (4^15)? Obviously, this is not enough, because 2 is also satisfies this condition. We additionally have to ensure it is a even power of 2. How to check it? One way is to use log function. Let x=log(num)/log(2), if x is a even number than num is power of 4.
Another way is that let x=num|0x55555555, if x==0x55555555 than num is power of 4, because 5 is 0101 in binary system, it filters the number that the most significant digit in odd position.
Code:
class Solution {
public:
bool isPowerOfFour(int num) {
if(num<=0)return false;
int HAT=1<<30;
if(HAT%num!=0)return false;
return (num|0x55555555)==0x55555555;
}
};
class Solution {
public:
bool isPowerOfFour(int num) {
if(num<=0)return false;
int HAT=1<<30;
if(HAT%num!=0)return false;
double x=log(num*1.0)/log(2.0);
int ix=x;
return ix%2==0;
}
};