Cho số nguyên num. Đếm tổng số bit 1 trong biểu diễn nhị phân (hàm __builtin_popcount).
Ví dụ: 50 (110010) → 3; 10 (1010) → 2.
Giải thuật: Dịch bit và đếm, hoặc dùng __builtin_popcount.
Ví dụ
#include <iostream>
using namespace std;
unsigned int bits(unsigned int number) {
unsigned int count = 0;
// Hiển thị 8-bit
for (unsigned i = 1 << 7; i > 0; i >>= 1)
cout << ((number & i) ? '1' : '0');
// Đếm bit 1
while (number) {
count += number & 1;
number >>= 1;
}
cout << "\nCount: " << count;
return count;
}
int main() {
bits(50);
return 0;
}
Đầu ra
8-bit digits of 50 is: 00110010 Count of total set bits in a number are: 3