#191

Number of 1 Bits

Easy n & (n-1)

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Count how many bits are set to 1 in the binary form of a number.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: how many switches are ON in this number?

Why this works: n & (n - 1) turns off the lowest ON bit. Count how many times you can do that before n is 0.

Example: n = 11 (1011)

1011 & 1010 = 1010  count 11010 & 1001 = 1000  count 21000 & 0111 = 0000  count 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using n >> 1 on a negative int in Java — the sign bit is copied in and the loop never ends. Use >>> or the n & (n - 1) loop.