[LeetCode] Problem 342 - Power of Four

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example

No.1

Input: 16

Output: true

No.2

Input: 5

Output: false

Follow up

Could you solve it without loops/recursion?

Code

1
2
3
4
5
6
7
public boolean isPowerOfFour(int num) {
if (num <= 0)
return false;

// 1010101010101010101010101010101
return (num & (num - 1)) == 0 && (num & 0x55555555) == num;
}