# Java 1-line (cheating for the purpose of not using loops)

• ``````    public boolean isPowerOfFour(int num) {
return num > 0 && (num&(num-1)) == 0 && (num & 0x55555555) != 0;
//0x55555555 is to get rid of those power of 2 but not power of 4
//so that the single 1 bit always appears at the odd position
}``````

• I got another 1 line solution, basically just change number to quaternary and then check if it starts with "10".

``````public boolean isPowerOfFour(int num) {
return Integer.toString(num, 4).matches("10*");
}
``````

• Good solution without good explanation,it's easy to find that power of 4 numbers have those 3 common features.First,greater than 0.Second,only have one '1' bit in their binary notation,so we use x&(x-1) to delete the lowest '1',and if then it becomes 0,it prove that there is only one '1' bit.Third,the only '1' bit should be locate at the odd location,for example,16.It's binary is 00010000.So we can use '0x55555555' to check if the '1' bit is in the right place.With this thought we can code it out easily!

• I think (num > 0) is a redundant check and can be safely removed. It is implicitly implied in the last two checks. Here is the reason:

1. if num == 0, the last test would fail;
2. if num < 0 and num != 0x80000000, there are alway at least two '1's in its binary representation (one of them is the MSB). It would fail the test (num & (num - 1)).
3. if num < 0 and num == 0x80000000, it would simply fail the last test again.

All the results from the above three conditions suggest the last two checks successfully cover the case where num <= 0. Therefore the first test (num > 0) is not necessary and thus can be removed. The code is slightly micro-optimized by (one?) instruction.

• This post is deleted!

• This post is deleted!

• This post is deleted!

• This post is deleted!

• brilliant bit manipulation, and I do not think this is cheating

• This post is deleted!

• This post is deleted!

• good explain

• good solution

• I saw a lot of solutions by using bit manipulation.

just wondering why no one uses Math.log(), Isn't it a short cut? Or it is a kind of cheating?

code below was accepted, it takes 2ms.

``````public boolean isPowerOfFour(int num) {
return (Math.log(num) / Math.log(4)) % 1 == 0;
}
``````

• Math.log() is slower than bitwise AND operation, I think...I have not looked for any reference about Math.log() complexity so correct me if I am wrong :)

• This post is deleted!

• fule you...........

• Have the same idea with you! but your code is more concise than mine

• Actually you don't need to add 'num > 0' in the beginning.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.