Check Power of 2 in JavaScript
What you’ll learn
- What powers of 2 are and where they appear in real coding tasks.
- How to use the
n & (n - 1)bit trick safely withn > 0. - How to list all powers of 2 in a range with clean JavaScript.
- Common edge cases with 0, negatives, and input parsing.
Overview
A positive integer is a power of 2 if it has exactly one 1 in binary.
Prerequisites
Basic JavaScript conditionals, loops, and bitwise operators.
What is a power of 2?
Values: 1, 2, 4, 8, 16, 32.... If a number cannot be reached by repeated doubling from 1, it is not a power of 2.
Live preview
Enter a value and test instantly.
Algorithm
1
Reject invalid values
If n <= 0, return false.
2
Bit test
Return (n & (n - 1)) === 0.
📜 Pseudocode
Pseudocode
if n <= 0: return false
return (n & (n - 1)) == 01
Check one number
JavaScript
function isPowerOfTwo(num) {
return num > 0 && (num & (num - 1)) === 0;
}
const number = 16;
if (isPowerOfTwo(number)) {
console.log(number + " is a power of 2.");
} else {
console.log(number + " is not a power of 2.");
}2
Power of 2 in range 1 to 20
JavaScript
function isPowerOfTwo(num) {
return num > 0 && (num & (num - 1)) === 0;
}
const values = [];
for (let i = 1; i <= 20; i++) {
if (isPowerOfTwo(i)) {
values.push(String(i));
}
}
console.log("Power of 2 in the range 1 to 20:");
console.log(values.join(" "));❓ FAQ
A whole number of the form 2^k for k >= 0. Examples: 1, 2, 4, 8, 16.
For positive n, it is true only when binary n has exactly one set bit.
Yes, because 2^0 = 1.
No for this tutorial. We require n > 0.
🔄 Input / output examples
| Input | Output |
|---|---|
| 16 | 16 is a power of 2. |
| 12 | 12 is not a power of 2. |
| 1 | 1 is a power of 2. |
| 0 | 0 is not a power of 2. |
Edge cases
n = 0Zero
Not treated as power of 2 in this tutorial.
Negative n
Invalid for this check
Return false for all negative values.
⏱️ Time and space complexity
| Method | Time | Space |
|---|---|---|
n & (n - 1) | O(1) | O(1) |
| Divide-by-2 loop | O(log n) | O(1) |
Summary
- Powers of 2 are positive values with one set bit in binary.
- Use
n > 0 && (n & (n - 1)) === 0for quick checks. - Handle 0 and negatives explicitly.
Did you know?
Many memory sizes and alignment rules in computing use powers of two, so this check appears often in interview rounds.
8 people found this page helpful
