AlgoMaster Logo

Number of 1 Bits

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

Counting the number of 1 bits in an integer can be approached by iterating through each bit and checking whether it is 1. This can be efficiently done by using bit shifts.

Steps:

  1. Initialize a counter to keep track of the number of 1 bits.
  2. Use a loop to iterate over each of the 32 bits of the integer.
  3. Use a bitmask to isolate each bit and determine if it's 1.
  4. For each bit that is 1, increment the counter.
  5. Return the counter as the result.

Code:

2. Bit Manipulation

Intuition:

The brute force approach can be optimized by using a clever trick with bit manipulation. By repeatedly turning off the rightmost 1-bit, we can directly count the 1-bits without checking each individual bit.

Each application of this operation removes one set bit. So if we repeat this process and count how many times it happens, the count equals the number of 1-bits.

This allows us to skip all zero bits and only operate on actual 1-bits making it much faster than a brute force bit scan.

Example Walkthrough

Let’s count the 1-bits in: n = 13 → binary: 1101

Steps:

  1. Initialize a counter to track the number of 1 bits.
  2. Loop while n is not zero.
  3. Apply n = n & (n - 1) to turn off the lowest 1-bit.
  4. Increment the counter.
  5. When all 1-bits are removed and n becomes zero, return the counter.

Code: