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
Code
JavaScript Programs
Start with the bitwise one-liner — that is the usual interview answer. List matches in a range, then keep the divide loop for explaining without bits. Each example has a Try it Yourself editor.
Example 1 — Bitwise Check
A positive power of two has exactly one set bit, so n & (n - 1) is zero.
JavaScript
function isPowerOfTwo(n) {
return n > 0 && (n & (n - 1)) === 0;
}
const number = 8;
if (isPowerOfTwo(number)) {
console.log(number + " is a power of 2");
} else {
console.log(number + " is not a power of 2");
}
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 — Powers of 2 from 1 to 20
Reuse the bitwise helper and print every match on one line.
JavaScript
function isPowerOfTwo(n) {
return n > 0 && (n & (n - 1)) === 0;
}
console.log("Powers of 2 from 1 to 20:");
let line = "";
for (let i = 1; i <= 20; i++) {
if (isPowerOfTwo(i)) {
line += i + " ";
}
}
console.log(line.trim());