For each number you are given, count how many bits are 1 in its binary form.
What to build
For each number x, repeat x &= x - 1 until x is 0, counting the steps. Each step removes one set bit.
Requirements
- Use
x & (x - 1), not a division loop - Use
long long
Input
The first line has t. Each of the next t lines has a number x.
Output
For each x, its number of one bits, one per line.
Constraints
1 ≤ t ≤ 1,000. 0 ≤ x ≤ 10¹⁸.
Example
Input:
4
0
1
44
255
Output:
0
1
3
8
Why it works
x & (x - 1) always clears the lowest one bit, so the loop runs exactly once for every one bit. The count is at most 60.
Examples
Example 1 · Input
4 0 1 44 255
Expected output
0 1 3 8
Example 2 · Input
2 1000000000000000000 7
Expected output
24 3
Hints
Hint 1
int count = 0; while (x > 0) { x &= x - 1; count++; }
Hint 2
0 has no one bits, so the loop does not run and prints 0.
Hint 3
Read x as long long.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
long long x;
cin >> x;
int count = 0;
while (x > 0) {
x &= x - 1;
count++;
}
cout << count << "\n";
}
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step