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?

Credits:
Special thanks to @yukuairoy for adding this problem and creating all test cases.


Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class {
public boolean isPowerOfFour(int num) {
if(num == 1) return true;
if(num <= 3) return false;
while(num > 1) {
if((num&1) == 1) {
return false;
}
num >>= 1;
if((num&1) == 1) {
return false;
}
num >>= 1;
}
return true;
}
}