231. Power of Two
Description of 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.
Example 1:
Input: n = 1
Output: true
Explanation: 20 = 1
Example 2:
Input: n = 16
Output: true
Explanation: 24 = 16
Example 3:
Input: n = 3
Output: false
Constraints:
-2^31 <= n <= 2^31 - 1
Follow up: Could you solve it without loops/recursion?
Solution 1 - Bitwise operations
Explanation
Consider binary number representation, each position is either 0 or 1 and it represents \(2^i\).
For any power of two, the binary representation should be \(1000......000000_2\).
Code (Java)
class Solution {
public boolean isPowerOfTwo(int n) {
if ( n <= 0 ){
return false;
}
while((n & 1) == 0){
n = n >> 1;
}
return n == 1 ;
}
}
Complexity
- n is the input number
Time complexity:
- \( T(n) = O(\log_2(n) + 1) \)
- Assume division takes constant time.
Auxiliary Space:
- \( S(n) = O(1) \)
Solution 2 - Meet the requirement of the follow-up
Explanation
The maximum power of two in i32 integer is \( 2^{30}=1073741824 \). This number is divsible by any power of two.
Code (Java)
class Solution {
public boolean isPowerOfTwo(int n) {
if (n <= 0) {
return false;
}else{
return (1073741824 % n) == 0;
}
}
}
Complexity
- n is the input number
Time complexity:
- \( T(n) = O(1) \)
- Assume division takes constant time.
Auxiliary Space:
- \( S(n) = O(1) \)