Given an integer n
, write a function to determine if it is a power of two.
n
?
n = 1
, Output: true
(since (2^0 = 1))n = 16
, Output: true
(since (2^4 = 16))n = 3
, Output: false
(since 3 is not a power of two)n = -16
, Output: false
(negative numbers are not powers of two)To determine if n
is a power of two, we can use the following properties:
1
bit in its binary representation.n
that is a power of two, ( n ) and ( n-1 ) have no common set bits. Hence n & (n-1) == 0
.Given these properties:
false
if n
is less than or equal to zero.n & (n-1)
is zero.#include <iostream>
bool isPowerOfTwo(int n) {
if (n <= 0) {
return false;
}
return (n & (n - 1)) == 0;
}
// Example usage:
int main() {
int testCases[] = {1, 16, 3, -16, 1024};
for (int n : testCases) {
std::cout << "isPowerOfTwo(" << n << ") = " << (isPowerOfTwo(n) ? "true" : "false") << std::endl;
}
return 0;
}
This solution efficiently checks whether the given number is a power of two, adhering to both time and space constraints expected in competitive programming.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?