# One of my favorite tricks

• Convert to double representation, which kinda takes the logarithm. Without precision problems. Then check the bit pattern.

``````bool isPowerOfFour(int num) {
double n = num;
return (*(long*)&n & 0x801FFFFFFFFFFFFF) == 0x10000000000000;
}
``````

There's probably a prettier way to use the idea, but I'll leave it at this.

• @StefanPochmann If it isn't too much trouble, can you please explain the logic. I know that this is one of the best ways to do this problem as I came across something similar online, but I am unable to understand it.

• @pb1771 Hmm, I already did explain it a bit. Do you understand the double representation? And please show that similar thing you came across, I'm curious to see it.

• @StefanPochmann Double precision is the part I didn't quite understand. Can you explain how it is logarithmic. The way I thought of doing it was by counting the number of trailing zeros to find if total number is even or odd (along with making sure that count of ones in binary representation is one). But it involves looping through it. Your method looks similar to a way of counting number of trailing zeros described here

• @pb1771 Roughly speaking, converting to double represents the number as `1.f * 2^e` with integers `f` (fraction) and `e` (exponent). Those two are stored and so I just check that the fraction is zero and that the exponent is even.

Thanks for the link. I think I've seen the page before, but never got around to working through it.

• @StefanPochmann Thank you so much for explaining this. I get it now :)

• Hi, I'm still confuse about the highest bit, why the highest bit of & result is 1? It seems that 1 indicate negative number?

• highest bit of & result is 1

What do you mean?

• @StefanPochmann Er, I mean why it is 0x10000000000000 in the right side, not 0x00000000000000 ?

• @daxietx That's not the highest bit. Highest bit would be 0x8000000000000000. The bit I do have there is the lowest bit of the stored exponent (which is actually shifted by 1023, an odd number, so ensuring the lowest bit is 1 means that the real exponent is even).

• This post is deleted!

• @StefanPochmann Ah I understand suddenly, thank you so much for your patience!!

• The same solution in Java:

``````    public boolean isPowerOfFour(int num) {
return (Double.doubleToLongBits(num) & 0x801FFFFFFFFFFFFFL) == 0x10000000000000L;
}
``````

• @ignath Neat. Didn't know that method yet, thanks. Much nicer than the hoops I'm jumping through in C++.

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