Evaluate if an integer is POT (Power Of Two)

Possible duplicates:
Request on whether the number is power 2
How to check if the number is power 2

I need a function body for this prototype:

bool isPOT(int x);

So it will return, for example, isPOT (3) = FALSE, but isPOT (8) = TRUE

What is the most beautiful or concise algorithm? And what is the most effective?

PS: I am amazed that I cannot find this question on SO, so I fully expect someone to find some kind of duplicate.

PPS: can someone create POT, NPOT, Power-Of-Two tags?

+5
source share
2 answers
bool IsPOT(int x)
{
    return (x > 0) && ((x & (x - 1)) == 0);
}
+12
source

Not sure if this exact question has arisen, but the check is simple

x & (x - 1) == 0
+6

All Articles