Description:
Given an integer n, return true if it is a power of four. Otherwise, return false.
An integer n is a power of four, if there exists an integer x such that n == 4x.
That is, while n equals to 1(=40), 4, 16, 64, 256,… then return true, otherwise return false.
Naive solution
Idea
Repeatedly divide n by 4, making sure the remainder equals 0 until the quotient equals 1.
bool isPowerOfFour(int n){
if (n<1) return false;
while(n!=1){
if (n%4 != 0) return false;
n/=4;
}
return true;
}
Another solution
Idea
The power of 4 in binary will start with one and end with an even number of zero.
- 1 = 0x1
- 4 = 0x100
- 16 = 0x10000
- …
Steps
two steps to check if n is the power of 4
- Use and operation to check lastest two bit is double zero
- Right offset with two-digit and check recursively.
bool isPowerOfFour(int n){
if (n<1){ return false; }
else if (n==1){ return true; }
else if ((n & 3) == 0) { return isPowerOfFour(n>>2);}
else { return false; }
}
Solution without loops/recursion
Idea
There’s a way to check if number is power of 2 with AND bitwise operation.
!(n & (n - 1))
Which and make sure n is power of 2.
And if n is power of 4 can be devided by 3 after subtract 1.
(n - 1) % 3 == 0
Combile all of them with check if n is larger then zero.
return n > 0 && !(n & (n - 1)) && (n - 1) % 3 == 0;
Notes
The pure bitwise operation get the shortest runtime on leetcode platform.