Cho số nhị phân 32-bit unsigned, đếm số bit '1' (set bits).
Ví dụ
N = 00000000000000100111
Output: 4
Cách tiếp cận
- Dùng hàm builtin STL:
__builtin_popcount(n)hoặcbitset<32>(n).count()
Code C++
#include <bits/stdc++.h>
using namespace std;
int count1bits(uint32_t n) {
return bitset<32>(n).count();
}
int main() {
uint32_t N = 0000000010100000011;
cout << count1bits(N) << endl;
return 0;
}
Kết quả
4
Có 4 bit '1' trong số nhị phân cho trước.