Skip to content
Problem 191 · LeetCode 191(opens in a new tab)

Number of 1 Bits

EasyBit manipulation

You are given a positive whole number n. Write it in binary and count how many of its digits are 1. That count is also called the number’s population count, or its Hamming weight.

Example 1

Input:  n = 13
Output: 3
Why:    13 is 1101 in binary
2 more examples and the constraints

Example 2

Input:  n = 64
Output: 1
Why:    64 is 1000000, a single 1

Example 3

Input:  n = 2147483647
Output: 31
Why:    the largest input is thirty-one 1s

Constraints

  • 1 ≤ n ≤ 2,147,483,647 (that is, 2³¹ − 1)

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Check every bitO(32)
  2. Clear the lowest set bitO(k)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeLoop rounds for n = 64Verdict
Check every bitO(32)
Passes; always 32 rounds
Clear the lowest set bitO(k)
Best; one round per 1 bit

k = how many bits of n are 1.

Edge cases to test

  • n = 1. One set bit: the loop runs once.
  • Powers of two. 64 has a single 1, so the best approach stops after one round.
  • The largest input. 2,147,483,647 has all 31 low bits set: the worst case for clearing bits.
  • Signed shifts. In Java and TypeScript, use >>> so a high bit is never copied in from the left.

Common mistakes

  • Looping while n > 0 with n >>= 1 in a language where the input can be a negative 32-bit pattern, so the loop never ends.
  • Writing n & n - 1 without knowing how the language orders & and -.
  • Counting digits of the decimal string instead of the binary one.

How to talk through it

  1. 1Clarify. Is n always positive? Is it a 32-bit value? Will this be called many times?
  2. 2Give the simple loop. Check each of the 32 bits with a shift and & 1.
  3. 3Show the trick. n − 1 flips the lowest 1 and the zeros below it, so n & (n − 1) removes that 1.
  4. 4Answer the follow-up. For many calls, a 256-entry table of 8-bit counts makes each call four lookups.
  5. 5Test out loud. Run 1, a power of two and 2³¹ − 1 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?