Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate if integer is POT (Power Of Two) [duplicate]

Possible Duplicates:
Query about working out whether number is a power of 2
How to check if a number is a power of 2

I require a function body for this prototype:

bool isPOT(int x);

So it would return eg isPOT(3) = FALSE, but isPOT(8) = TRUE

What is the most pretty/concise algorithm? And what is the most efficient?

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

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

like image 770
P i Avatar asked Mar 05 '11 07:03

P i


2 Answers

bool IsPOT(int x)
{
    return (x > 0) && ((x & (x - 1)) == 0);
}
like image 176
Paul R Avatar answered Nov 14 '22 08:11

Paul R


Not sure if this exact question occurred, but the check is easy

x & (x - 1) == 0
like image 37
Nikita Rybak Avatar answered Nov 14 '22 08:11

Nikita Rybak