Article start
DSA Course: Interview Patterns and Problem Solving
Module 14: Bit Manipulation

Number of 1 Bits: Brian Kernighan Pattern

Count set bits by repeatedly removing the lowest set bit.

May 29, 2026·27

Learning Outcome

After this lesson, you should be able to count set bits by clearing one set bit per loop.

Problem Statement

Given an integer n, return the number of 1 bits in its binary representation.

InputOutputWhy
n = 11311 is binary 1011, which has three set bits.

Brute Force Approach

Check every bit position one by one. This is fine for fixed width but does unnecessary work for sparse numbers.

Optimized Approach

Use Brian Kernighan's trick: n & (n

    1. removes the lowest set bit each time, so the number of loop iterations equals the number of 1 bits.

Exact Pseudocode

count = 0
while n != 0:
  n = n & (n - 1)
  count += 1
return count

Reference Code

class Solution:
    def hammingWeight(self, n):
        count = 0
        while n:
            n &= n - 1
            count += 1
        return count

Sample Dry Run

StepStateResult
n = 11binary 1011count = 0
Clear bit 11011 -> 1010count = 1
Clear bit 21010 -> 1000count = 2
Clear bit 31000 -> 0000count = 3

Complexity

MeasureValueReason
TimeO(number of set bits)The loop runs once per set bit.
SpaceO(1)Only the count variable is stored.

Edge Cases

  • n = 0 should return 0.
  • Use unsigned types in C++ when the prompt treats n as unsigned.
  • A signed right shift approach can be tricky for negative values.

Interview Checklist

  • Use n &= n

    • 1 to remove one set bit.
  • Increment count once per removal.
  • Stop when n becomes zero.

FAQs

Why is this faster for sparse numbers?

It skips zero bits entirely and loops only over set bits.

What does Brian Kernighan's trick clear?

It clears the lowest set bit.

What is the core pattern?

Repeated lowest-set-bit removal.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.