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
Austin Powers in Python
Suppose we have a number greater than 0, we have to check whether the number is a power of two or not. A power of two is any number that can be expressed as 2n where n is a non-negative integer (1, 2, 4, 8, 16, 32, etc.).
So, if the input is like 1024, then the output will be True because 1024 = 210.
Approach
To solve this, we will follow these steps ?
-
While n > 1, do
n := n / 2
Return true when n is same as 1, otherwise false
Let us see the following implementation to get better understanding ?
Example
class Solution:
def solve(self, n):
while n > 1:
n /= 2
return n == 1
ob = Solution()
print(ob.solve(1024))
print(ob.solve(18))
print(ob.solve(16))
True False True
Alternative Approach Using Bit Operations
A more efficient way is to use the bit manipulation trick. A power of two has only one bit set in its binary representation ?
def is_power_of_two(n):
if n <= 0:
return False
return (n & (n - 1)) == 0
# Test with different numbers
numbers = [1, 2, 4, 8, 16, 32, 64, 1024, 18, 100]
for num in numbers:
result = is_power_of_two(num)
print(f"{num} is power of two: {result}")
1 is power of two: True 2 is power of two: True 4 is power of two: True 8 is power of two: True 16 is power of two: True 32 is power of two: True 64 is power of two: True 1024 is power of two: True 18 is power of two: False 100 is power of two: False
How It Works
The bit manipulation approach works because:
Powers of two have exactly one bit set: 8 = 1000, 16 = 10000
When we subtract 1, all bits after the set bit become 1: 8-1 = 0111
The AND operation between n and (n-1) gives 0 for powers of two
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
| Division Loop | O(log n) | Easy to understand |
| Bit Manipulation | O(1) | Most efficient |
Conclusion
Use the bit manipulation approach n & (n-1) == 0 for the most efficient solution. The division method is easier to understand but slower for large numbers.
