0

I’m trying to implement a function like

auto Solution(int num, int k)
{
    std::vector<int> result;
    ...
    return result;
} 

For example, Solution(5, 6) return vector = {0,0,0,1,0,1}. Solution(4, 3) return vector = {1,0,0}. I'm new c++ beginner and don't know how to do it

1 Answers1

0

For the first of all I advice you to use std::bitset to handle bits. And if you need to store each bit separately in vector use smallest integer size (e.g. int8_t).

And I think even in my example usage of std::vector is excessively. You can access bits object directly like a regular array of 0 and 1 values. In C++ you don't really need bitwise operations to separate integer for individual bits.

auto Solution(int num, int k)
{
    std::bitset<sizeof(num) * 8> bits(num);
    std::vector<int8_t> result(k);
    for (int i = 0; i < k; i++)
        result[i] = bits[i];
    return result;
}