Hello,
Does anyone know how to count the number of 1's and 0's in a binary sequence.
Hello,
Does anyone know how to count the number of 1's and 0's in a binary sequence.
You can put it in a bitset and use the count member function
If it happens to already be in a string/character-array form you could also use the STL count_if function.
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens
or just the std::count() see last example:Originally Posted by hk_mp5kpdw
Code:#include <bitset> #include <string> #include <iostream> #include <algorithm> const unsigned number = 15122; int countBits(unsigned n) { unsigned count = 0; while(n) { if (n&1)count++; n = n>>1; } return count; } int main() { std::string str = std::bitset<32>(number).to_string(); std::cout << countBits(number) << "\n"; std::cout << std::bitset<32>(number).count() << "\n"; std::cout << std::count(str.begin(), str.end(),'1')<< "\n"; }