#include <iostream>
#include <bit>
#include <cmath>
using std::cout;
// 1) Bitwise trick: x & (x - 1) == 0
bool is_power_of_two_a(unsigned int x) {
return x != 0 && (x & (x - 1)) == 0;
}
// 2) Count bits using std::popcount (C++20)
bool is_power_of_two_b(unsigned int x) {
return x != 0 && std::popcount(x) == 1;
}
// 3) Using std::has_single_bit (C++20)
bool is_power_of_two_c(unsigned int x) {
return std::has_single_bit(x);
}
// 4) Using logarithms (educational)
bool is_power_of_two_d(unsigned int x) {
if (x == 0) return false;
double y = log2(x);
return floor(y) == y;
}
int main() {
unsigned int a = 64; // true
unsigned int b = 70; // false
cout << std::boolalpha;
cout << "Testing " << a << ":\n";
cout << is_power_of_two_a(a) << "\n";
cout << is_power_of_two_b(a) << "\n";
cout << is_power_of_two_c(a) << "\n";
cout << is_power_of_two_d(a) << "\n\n";
cout << "Testing " << b << ":\n";
cout << is_power_of_two_a(b) << "\n";
cout << is_power_of_two_b(b) << "\n";
cout << is_power_of_two_c(b) << "\n";
cout << is_power_of_two_d(b) << "\n";
}
/*
OUTPUT:
Testing 64:
true
true
true
true
Testing 70:
false
false
false
false
*/