#include <stdio.h>
#include <math.h>
#include <stdbool.h>
// Method A: Bit-counting
bool isPowerOfTwoA(int x) {
if (x <= 0) return false;
int count = 0;
while (x > 0) {
if (x & 1) count++;
x >>= 1;
}
return count == 1;
}
// Method B: Bitwise trick
bool isPowerOfTwoB(int x) {
return x > 0 && (x & (x - 1)) == 0;
}
// Method C: Repeated division
bool isPowerOfTwoC(int x) {
if (x <= 0) return false;
while (x % 2 == 0) {
x /= 2;
}
return x == 1;
}
// Method D: Using logarithms
bool isPowerOfTwoD(int x) {
if (x <= 0) return false;
double logv = log(x) / log(2);
return fabs(logv - round(logv)) < 1e-10;
}
int main() {
int test1 = 16; // true
int test2 = 18; // false
printf("A: %s, %s\n", isPowerOfTwoA(test1) ? "true" : "false",
isPowerOfTwoA(test2) ? "true" : "false");
printf("B: %s, %s\n", isPowerOfTwoB(test1) ? "true" : "false",
isPowerOfTwoB(test2) ? "true" : "false");
printf("C: %s, %s\n", isPowerOfTwoC(test1) ? "true" : "false",
isPowerOfTwoC(test2) ? "true" : "false");
printf("D: %s, %s\n", isPowerOfTwoD(test1) ? "true" : "false",
isPowerOfTwoD(test2) ? "true" : "false");
return 0;
}
/*
OUTPUT:
A: true, false
B: true, false
C: true, false
D: true, false
*/