Problem: Check if a Number is a Power of Two
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: 2^0 = 1
Example 2:
Input:
n = 16
Output:
true
Explanation: 2^4 = 16
Example 3:
Input:
n = 3
Output:
false
Constraints:
nis a positive integer.
Approach:
A number n is a power of two if and only if it has exactly one bit set in its binary representation. For example:
1(binary0001) is2^02(binary0010) is2^14(binary0100) is2^28(binary1000) is2^3
Using the property that for any power of two, n & (n - 1) will be 0, we can check if the number is a power of two.
C Code:
#include <stdio.h>
#include <stdbool.h>
bool isPowerOfTwo(int n) {
// Check if n is greater than 0 and if n & (n - 1) is 0
return (n > 0) && (n & (n - 1)) == 0;
}
int main() {
int n;
printf("Enter an integer: ");
scanf("%d", &n);
if (isPowerOfTwo(n)) {
printf("%d is a power of two.n", n);
} else {
printf("%d is not a power of two.n", n);
}
return 0;
}
Explanation:
-
n & (n - 1): This bitwise operation works because for any power of two, its binary representation has only one bit set to1. Subtracting1from a power of two flips all the bits after the most significant1, and the&operation results in0.- For example:
n = 16(binary10000),n - 1 = 15(binary01111), so16 & 15 = 0.n = 8(binary1000),n - 1 = 7(binary0111), so8 & 7 = 0.
- For example:
-
Check: The function first ensures that
n > 0because negative numbers or zero can’t be powers of two. Then, it checks if the bitwise operation returns0, which confirms thatnis a power of two.
Time Complexity:
- The time complexity of this solution is
O(1)because the bitwise operations are constant-time operations.
Example Output:
Input:
Enter an integer: 16
Output:
16 is a power of two.
