Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Check for Power of two in JavaScript
We need to write a function, isPowerOfTwo(), that takes a positive number and returns a boolean based on whether the number is a power of 2.
For example:
isPowerOfTwo(3) // false (3 is not a power of 2) isPowerOfTwo(32) // true (32 = 2^5) isPowerOfTwo(2048) // true (2048 = 2^11) isPowerOfTwo(256) // true (256 = 2^8) isPowerOfTwo(22) // false (22 is not a power of 2)
Method 1: Using Recursive Division
This approach recursively divides the number by 2 until it reaches 1 (power of 2) or becomes odd (not a power of 2):
const isPowerOfTwo = num => {
if (num === 1) {
return true;
}
if (num % 2 !== 0) {
return false;
}
return isPowerOfTwo(num / 2);
}
console.log(isPowerOfTwo(3));
console.log(isPowerOfTwo(32));
console.log(isPowerOfTwo(2048));
console.log(isPowerOfTwo(256));
console.log(isPowerOfTwo(22));
false true true true false
Method 2: Using Bitwise AND Operation
A more efficient approach uses the mathematical property that powers of 2 have only one bit set. For any power of 2 n, the expression n & (n-1) equals 0:
const isPowerOfTwoBitwise = num => {
return num > 0 && (num & (num - 1)) === 0;
}
console.log(isPowerOfTwoBitwise(3));
console.log(isPowerOfTwoBitwise(32));
console.log(isPowerOfTwoBitwise(2048));
console.log(isPowerOfTwoBitwise(256));
console.log(isPowerOfTwoBitwise(22));
false true true true false
How the Bitwise Method Works
Powers of 2 in binary have exactly one bit set:
8 (2^3): 1000 8-1 = 7: 0111 8 & 7: 0000 ? equals 0 16 (2^4): 10000 16-1 = 15: 01111 16 & 15: 00000 ? equals 0
Comparison
| Method | Time Complexity | Space Complexity | Approach |
|---|---|---|---|
| Recursive Division | O(log n) | O(log n) | Divide by 2 repeatedly |
| Bitwise AND | O(1) | O(1) | Single bitwise operation |
Conclusion
The bitwise method n & (n-1) === 0 is the most efficient way to check powers of 2. It runs in constant time and uses the mathematical property that powers of 2 have exactly one bit set in binary.
Advertisements
