Finding if a number is a power of 2

Subtract 1 from the number, then and it with the original number. If the result is zero, it was a power of two.

if (((n-1) & n) == 0) {
    // power of two!
}

(sorry, my PHP is rusty...)


If it's a power of 2? Well, one way is to convert it to binary, and verify the presence of only 1 1...:

$bin = decbin($number);
if (preg_match('/^0*10*$/', $bin)) {
    //Even Power Of 2
}

One way is to use bitwise AND. If a number $x is a power of two (e.g., 8=1000), it will have no bits in common with its predecessor (7=0111). So you can write:

($x & ($x - 1)) == 0

Note: This will give a false positive for $x == 0.

Tags:

Php