# O(1) one-line solution without loops

• ``````public class Solution {
public boolean isPowerOfFour(int num) {
return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0x55555555) == num);
}
}
``````

The basic idea is from power of 2, We can use "n&(n-1) == 0" to determine if n is power of 2. For power of 4, the additional restriction is that in binary form, the only "1" should always located at the odd position. For example, 4^0 = 1, 4^1 = 100, 4^2 = 10000. So we can use "num & 0x55555555==num" to check if "1" is located at the odd position.

• Nice, but the last check why didn't you use only 0x55555555 ?

• This post is deleted!

• Yep, 0x55555555 is good enough for this question. I updated the code based on your suggestion

• This post is deleted!

• This post is deleted!

• This post is deleted!

• public class Solution {
public static final int mask = 0x55555555;
public boolean isPowerOfFour(int num) {
if((num & (num - 1)) != 0)
return false;
return false;
return true;
}
}

• why bother to check "num > 0"? if it is negative, it will fail "num & 0x55555555 == num" check anyway.

• negative number cannot be power of 4

• Checking num > 0 is for the case when num==0, in which (num & (num-1) == 0) and ((num & 0x55555555)==num).

• 0x6666666666666666

• @diegozeng

(num & (num - 1)) == 0
this piece of code turns out to be false, while
!(num & (num - 1))
is true.

I couldn't figure out why. It's weird.

• Another one liner in Java
public boolean isPowerOfFour(int num) {
return Integer.bitCount(num) == 1 && (Integer.toBinaryString(num).length()-1)%2==0;
}

• @diegozeng Could you please explain your solution? I understood your first two checks - but not the third one. How does `(num & 0x55555555) == num` check if `num` has `1`s only at the odd places?

• Really nice and smart idea.

• @BatCoder

Every power of 2:

0000 0001 = 1
0000 0010 = 2
0000 0100 = 4
0000 1000 = 8
0001 0000 = 16
0010 0000 = 32
0100 0000 = 64
1000 0000 = 128

Every other power of 2 is a power of 4. 0x55 is used as the bitmask to obtain every other power of 2 as follows by bitwise AND. I've left the values which align with 1s in the bitmask "as is", and I have crossed-out the values which align with 0s in this bitmask.

0101 0101 = 0x55

0000 0001 = 1
0000 0010 = 2
0000 0100 = 4
0000 1000 = 8
0001 0000 = 16
0010 0000 = 32
0100 0000 = 64
1000 0000 = 128

• @claytonjwong Thank you for your answer. Could you kindly elaborate with an example? That would be very helpful.

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