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.
-2^31 <= n <= 2^31 - 1Use iterative division to check if a number is a power of two. A number n is a power of two if it can be written as 2^k where k ≥ 0.
Algorithm:
n is less than or equal to 0, return false (powers of two must be positive)n is even (divisible by 2), divide n by 2n equals 1, then it was a power of twoThis approach works because:
Alternative approaches include:
n > 0 && (n & (n - 1)) == 0Example 1: n = 16
Step-by-step execution:
Example 2: n = 12
Step-by-step execution:
Example 3: n = 1
Step-by-step execution:
Example 4: n = 0
Step-by-step execution:
class Solution {
public boolean isPowerOfTwo(int n) {
if (n <= 0)
return false;
while (n % 2 == 0) {
n = n / 2;
}
return n == 1;
}
}
class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
}
Explanation: Powers of two have exactly one ‘1’ bit in binary. Using n & (n - 1) clears the least significant ‘1’ bit. If result is 0 and n > 0, then n is a power of two.
Time Complexity: O(1) - single bitwise operation Space Complexity: O(1) - constant space