Problem 82
Count Set Bits
Easy · 10 pts · Bit Manipulation
Problem
You are given a non-negative integer N. Print the number of 1 bits (set bits) in its binary representation. You can check the bits one at a time with N & 1 and shift N right until it becomes 0. A neat trick is N & (N - 1), which clears the lowest set bit, so the number of times you can apply it before N reaches 0 is the answer. N can be as large as 2^60 - 1 (about 1.15 × 10^18), so use a 64-bit integer.
Input
A single integer N.
Output
Print the number of set bits.
Constraints
0 <= N < 2^60
Example input
11
Example output
3
Explanation
11 in binary is 1011 (8 + 2 + 1). It contains three 1 bits, so the answer is 3.