Or keep dividing by 2 while $n is even; end at 1 if it is a power of two.
Reject zero and negatives before either test.
Method
Idea
Time
Best for
Bitwise
$n > 0 && ($n & ($n - 1)) === 0
O(1)
Interviews, production
Divide by 2
Halve until odd / reach 1
O(log n)
Explaining without bits
Pseudocode
Pseudocode
function IsPowerOfTwo(n):
return n > 0 and (n & (n - 1)) == 0
// Loop alternative:
function IsPowerOfTwoLoop(n):
if n <= 0: return false
while n % 2 == 0:
n = n / 2
return n == 1
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
One-liner
$n > 0 && ($n & ($n - 1)) === 0
Why it works
Powers of two have a single set bit
1
2^0 — yes
0
Not a power of two
Negatives
Not in this tutorial
Classic checks
8 yes; 6 no; 16 yes
Try it
Live Preview
Enter an integer to see the bitwise check and the power-of-two verdict.
Whole numbers only. Tap a chip or type a value.
Result
n = 8
n - 1 = 7
n & (n - 1) = 0
8 is a power of 2
Trace
Worked Walkthrough — n = 8
Show the bitwise identity, then the same answer by dividing.
Calculation
Bitwise:
8 in binary = 1000
7 in binary = 0111
1000 & 0111 = 0000 → power of 2
Divide-by-2 loop:
8 / 2 = 4
4 / 2 = 2
2 / 2 = 1
stop at 1 → power of 2
Counterexample n = 6:
6 = 110, 5 = 101
110 & 101 = 100 ≠ 0 → not a power of 2
Code
PHP Programs
Start with the bitwise one-liner — that is the usual interview answer. Keep the divide loop ready when you need to explain without bits.
Example 1 — Bitwise Check
A positive power of two has exactly one set bit, so $n & ($n - 1) is zero.
php
<?php
function isPowerOfTwo($n) {
return $n > 0 && ($n & ($n - 1)) === 0;
}
$number = 8;
echo $number . (isPowerOfTwo($number) ? " is a power of 2\n" : " is not a power of 2\n");
?>
Output
8 is a power of 2
How It Works
$n > 0 rejects zero and negatives up front.
$n - 1 clears the lowest set bit of $n and turns on all bits below it.
For a single-bit number like 8 (1000), that AND becomes 0.
If two or more bits are set (like 6), the AND is nonzero.
Constant-time check — the default answer in interviews.
Example 2 — Divide-by-2 Loop
Keep dividing even values by 2; a power of two ends exactly at 1.