How to get a list of powers of 2 of bits of a number whose sum is equal to the number in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <cmath>

// 365 = 000101101101 = 0(2^11) + 0(2^10) + 0(2^9) + 1(2^8) + 
// 0(2^7) + 1(2^6) + 1(2^5) + 0(2^4) + 1(2^3) + 1(2^2) + 0(2^1) + 
// 1(2^0) = 256 + 64 + 32 + 8 + 4 + 1 = 365

std::vector<int> get_all_powers_of_two(int n) {
    std::vector<int> result;
    int power_of_two = 1; // Start with 2^0

    while (n > 0) {
        // Check if the least significant bit is 1
        if (n & 1) {
            result.push_back(power_of_two);
        }
        
        // Right shift n to check the next bit
        n >>= 1; 
        
        // Double the power of two for the next position
        power_of_two <<= 1; 
    }
    
    return result;
}

int main() {
    int x = 365; // 000101101101
    std::vector<int> powers = get_all_powers_of_two(x);

    std::cout << "Powers of 2 for " << x << ": [ ";
    for (int p : powers) {
        std::cout << p << " ";
    }
    std::cout << "]" << std::endl;

    return 0;
}


/*
OUTPUT:

Powers of 2 for 365: [ 1 4 8 32 64 256 ]
   
*/

 



answered Apr 4 by avibootz
...