Number of 1 Bits

EasyBits and mathAlso known as LeetCode 191

You get a non-negative integer. Return the number of bits that are 1 in its binary representation. This count is sometimes called the Hamming weight.

For example 11 is 1011 in binary, which has three 1 bits.

Examples

Input n = 11
Output 3
11 is 1011 in binary.
Input n = 128
Output 1
128 is 10000000 in binary.
Input n = 2147483645
Output 30
Only one bit of the 31 low bits is 0.

Constraints

  • 0 <= n <= 2,147,483,647

Stuck? Take one hint at a time

Common mistakes
  • Using a right shift on a negative number in a language that keeps the sign bit, so n never reaches 0 and the loop never ends.
  • Counting digits of the decimal number instead of bits of the binary number.
  • Writing while (n > 0) in a language where n could be negative, which stops at once. Here n is never negative, but know why the loop is safe.
Questions an interviewer may ask next
  • Count the 1 bits for every number from 0 to n. (Counting Bits: reuse earlier answers.)
  • The function will be called a million times on 32 bit values. How would you speed it up? (A lookup table of 256 entries, or the hardware popcount instruction.)
  • Allow negative numbers as 32 bit two's complement. What changes in a language where a right shift keeps the sign?
  • Find the number of bit positions where two numbers differ. (XOR them, then count the 1 bits.)