Dare2Solve
The problem requires checking whether a given integer n
is a power of two. A number is a power of two if it can be expressed as 2^k
where k
is a non-negative integer. For example, 1 (2^0)
, 2 (2^1)
, 4 (2^2)
, 8 (2^3)
, etc., are all powers of two.
A power of two has only one bit set in its binary representation (e.g., 1
, 2
, 4
, 8
are 0001
, 0010
, 0100
, 1000
in binary, respectively). Therefore, one intuitive way to check if a number is a power of two is to iterate through the powers of two and compare each with n
.
Iterative Comparison:
2^30
is the largest power of two within the range of a 32-bit signed integer.n
.n
, return true
.false
.Edge Cases:
n = 0
(which is not a power of two) and negative numbers, which are also not powers of two.O(1). The loop runs a fixed number of iterations (31 iterations for a 32-bit integer), so the time complexity is constant.
O(1). The algorithm uses a fixed amount of extra space, regardless of the input size.
class Solution {
public:
bool isPowerOfTwo(int n) {
for (int i = 0; i < 31; i++) {
if (pow(2, i) == n) {
return true;
}
}
return false;
}
};
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
for i in range(31):
if 2 ** i == n:
return True
return False
class Solution {
public boolean isPowerOfTwo(int n) {
for (int i = 0; i < 31; i++) {
if (Math.pow(2, i) == n) {
return true;
}
}
return false;
}
// Usage Example
public static void main(String[] args) {
Solution sol = new Solution();
boolean result = sol.isPowerOfTwo(16); // Example input
System.out.println(result); // Output: true
}
}
var isPowerOfTwo = function (n) {
for (i = 0; i < 31; i++) {
if (Math.pow(2, i) == n) {
return true
}
}
return false
};