Problem
Given an integer n
, return true
if it is a power of two. Otherwise, return false
.
An integer n
is a power of two, if there exists an integer x
such that n == 2^x
.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Simple Division and Modulo Operator - Iterative Approach
We divide a number (N) by 2 repeatedly. If it remains even and reaches 1, N is a power of 2. However, division by zero is undefined, so N cannot be a power of 2 if it’s zero.
Code
|
|
Complexity
- ⏰ Time complexity:
O(log n)
- 🧺 Space complexity:
O(1)
Method 2 - Simple Division and Modulo Operator - Recursive Approach
|
|
Complexity
- ⏰ Time complexity:
O(log n)
- 🧺 Space complexity:
O(1)
Method 3 - Count Bits with user-defined function
|
|
We can make it slightly faster:
|
|
Method 4 - Count Bits with Standard Library
|
|
Method 5 - Using Bitwise and with N & (N-1)
|
|
Why N&(N-1) works? Read more here - Explain (n & (n-1)) == 0.
Method 6 - Using Logarithms
|
|
Above solution easily works in c++, for java:
|
|
Note that above code works for Math.log10
but doesn’t for Math.log
.
Method 7 - Using Integer.Max_Value and Division
Because the range of an integer = -2147483648 (-2^31)
~ 2147483647 (2^31-1)
, the max possible power of two = 2^30 = 1073741824
.
- If
n
is the power of two, letn = 2^k
, wherek
is an integer. We have 2^30 = (2^k) * 2^(30-k), which means (2^30 % 2^k) == 0. - If
n
is not the power of two, letn = j*(2^k)
, wherek
is an integer andj
is an odd number.
We have (2^30 % j*(2^k)) == (2^(30-k) % j) != 0.
|
|
Complexity
- ⏰ Time complexity:
O(1)
- 🧺 Space complexity:
O(1)