First of all, your algorithm simply displays the binary representation of some number n
, instead of dividing it into single digits and returning some set of their binary representation.
To make out lives easier, we will be using standard containers and standard algorithms:
[...] if i have a number like 215 for example, i seperate each number [2,1,5] and then covert each number into binary so it would be 0010,0001,0101
Great, it means that we need some sort of a container to hold those three representations, don't we? My choice would be std::vector
, since it is incredibly simple and efficient! You can read more about it here.
The mentioned vector
will eventually store the binary representations, but here we encounter another problem - we actually need to somehow represent them!
Fortunately enough, the standard gives us a great tool - std::bitset
, which is explained here. It is primarily used to make binary operations easier, but one of its great features is that it's also extremely good at simply being a binary representation.
The final function could look like this:
auto dec_to_bin(int n)
{
std::vector<std::bitset<4>> repr;
while(n > 0){
repr.push_back(std::bitset<4>(n % 10));
n /= 10;
}
std::reverse(repr.begin(), repr.end());
return repr;
}
What is happening here?
We firstly create a vector
of fixed size bitsets (of the size 4, since every decimal digit can be represented as four binary digits), then as long as our n
is greater than zero (you already know why - you are using the same logic in your code), we add (using push_back
) a new bitset, that will be treated as binary representation of modulo of your number (i.e. the last digit).
Keep in mind though, that by doing this, we created the vector
in the reversed order. The last two things we have to do is simply reverse
and return it!
Finally, we can use our function in main
as such:
int main()
{
for(auto b : dec_to_bin(215)){
std::cout << b << ' ';
}
}
This will print 0010 0001 0101
, which was your desired output for the number 215