Skills101
← All coding problems

Number of 1 Bits

easyBit Manipulation+10 XPTime limit 2s

For each number, count the 1 bits in its binary representation (its Hamming weight or popcount). For example 11 = 1011₂ has three.

Input:

  • line 1: q
  • next q lines: one non-negative integer x each

Output: for every x, its number of 1 bits on its own line.

Constraints: 1 ≤ q ≤ 10⁵, 0 ≤ x < 2³².

Watch out: x can be ≥ 2³¹, so it does not fit in a signed 32-bit int — use long / long long / unsigned. Trick: x & (x − 1) removes the lowest set bit, so the loop runs only once per 1 bit.

Sample input 1

3
11
128
4294967293

Sample output 1

3
1
31

Sample input 2

2
0
1

Sample output 2

0
1

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.