Skip to main content
71

Number of 1 Bits

Easybit manipulation

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Bit ManipulationRead the beginner guide

Given an unsigned 32-bit integer n, return the number of 1 bits in its binary representation (also called its Hamming weight or popcount).

Understand the problem

  • Every number can be written in binary, using only 0s and 1s: 11 is 1011 (8 + 2 + 1). Each digit is a bit.
  • You count how many of those bits are 1.
  • Unsigned 32-bit means n is between 0 and 2^32 - 1, so it fits in 32 bits and is never negative.

Example 1

text
Input:  n = 11
Output: 3

11 is 1011 in binary: three 1s.

Example 2

text
Input:  n = 128
Output: 1

128 is 10000000: a single 1.

Example 3

text
Input:  n = 4294967293
Output: 31

That's 11111111111111111111111111111101: 31 ones and a single 0.

Constraints

  • 0 <= n <= 2^32 - 1

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    n & (n - 1) removes the lowest 1 bit of n, so count how many times you can do that before n becomes 0.

    A quick binary refresher

    Numbers in binary use only 0 and 1, and each position is worth double the one to its right: 1, 2, 4, 8, .... So 1011 is 8 + 0 + 2 + 1 = 11.

    The bitwise operators work on each bit position separately:

    OperatorNameResult bit is 1 when...Example
    a & bANDboth bits are 11100 & 1010 = 1000
    a | bORat least one bit is 11100 | 1010 = 1110
    a ^ bXORthe bits are different1100 ^ 1010 = 0110
    a >> 1shift rightevery bit moves one place right; the lowest falls off1011 >> 1 = 101

    Approach 1: check each bit

    n & 1 is the lowest bit. Add it to a count, shift n right by one, and repeat until n is 0. This takes up to 32 steps.

    The key insight: n & (n - 1) drops the lowest 1

    Subtracting 1 from a binary number turns its lowest 1 into a 0, and every 0 below it into 1. Everything above stays the same. So when you AND it with the original, the lowest 1 and everything below it become 0, and everything above is unchanged:

    text
    n     = 1011 0100
    n - 1 = 1011 0011
    &     = 1011 0000     the lowest 1 is gone

    Repeat n = n & (n - 1) until n is 0, counting the steps. Each step removes exactly one 1, so the loop runs once per 1 bit, not 32 times. This is called Brian Kernighan's trick.

    Step by step

    n = 11 (1011):

    Stepnn - 1n & (n - 1)Count
    11011101010101
    21010100110002
    31000011100003

    n is now 0. Answer: 3.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(number of 1 bits), at most 32.
    • Memory: O(1).

    Common mistakes

    • In JavaScript, looping while (n > 0). For large inputs, n & (n - 1) gives a negative number (JavaScript's bitwise operators use signed 32-bit integers), and the loop would stop early. Use while (n !== 0).
    • Using >> instead of >>> in JavaScript in approach 1. >> copies the sign bit, so a negative number never reaches 0.
    • Converting to a string (n.toString(2)) and counting '1's. It works, but interviewers want the bitwise version.

    Going deeper

    • n & (n - 1) === 0 checks whether n is a power of two (exactly one 1 bit). A classic one-liner.
    • Counting Bits asks for the count for every number from 0 to n, and reuses these ideas with DP.

    Reference solution

    js
    /**
     * @param {number} n
     * @return {number}
     */
    export default function hammingWeight(n) {
      let count = 0
      // !== 0, not > 0: JS bitwise results are signed, so n can go negative along the way.
      while (n !== 0) {
        n &= n - 1 // turn off the lowest 1 bit
        count++ // one step per 1 bit
      }
      return count
    }
    ts
    export default function hammingWeight(n: number): number {
      let count = 0
      // !== 0, not > 0: JS bitwise results are signed, so n can go negative along the way.
      while (n !== 0) {
        n &= n - 1 // turn off the lowest 1 bit
        count++ // one step per 1 bit
      }
      return count
    }
    python
    def hamming_weight(n: int) -> int:
        count = 0
        while n:
            n &= n - 1  # turn off the lowest 1 bit
            count += 1  # one step per 1 bit
        return count