Numbers and bits · 8 / 15 Exercise Easy

Count set bits

Objective

The popcount of a number is the amount of 1 bits in its binary form. The trick n & (n - 1) always clears the lowest set bit, so repeating it until you reach 0 counts the bits without walking over all of them.

Instructions

  • The input is a line with non-negative integers separated by spaces.
  • Show, one per line, the number of 1 bits of each number.
Input
0 1 7 8 255
Output
0
1
3
1
8

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise