How to write 5 different functions that check if a number is a power of 2 in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#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 builtin popcount (portable)
bool is_power_of_two_b(unsigned int x) {
    return x != 0 && __builtin_popcount(x) == 1;
}

// 3) Manual bit counting (no builtins)
bool is_power_of_two_c(unsigned int x) {
    int count = 0;
    while (x) {
        count += x & 1;
        x >>= 1;
    }
    return count == 1;
}

// 4) Logarithmic method
bool is_power_of_two_d(unsigned int x) {
    if (x == 0) return false;
    double y = log2(x);
    return floor(y) == y;
}

// 5) Python‑style: convert to binary string and count '1'
bool is_power_of_two_e(unsigned int x) {
    if (x == 0) return false;
    std::string s;
    while (x) {
        s.push_back((x & 1) ? '1' : '0');
        x >>= 1;
    }
    int ones = 0;
    for (char c : s) if (c == '1') ones++;
    return ones == 1;
}

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";
    cout << is_power_of_two_e(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";
    cout << is_power_of_two_e(b) << "\n";
}



/*
OUTPUT: 

Testing 64:
true
true
true
true
true

Testing 70:
false
false
false
false
false
  
*/

 



answered Apr 2 by avibootz

Related questions

...