#191

Number of 1 Bits

Easy
Divide and ConquerBit ManipulationBit ManipulationCounting Bits
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

The optimal solution uses bit manipulation to count the set bits directly without converting to a string. This is much faster and more efficient, especially for large numbers.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a count variable to 0.
  2. 2Step 2: While n is greater than 0, perform the following: - Increment the count if the least significant bit (LSB) is 1 (n & 1). - Right shift n by 1 (n >>= 1).
  3. 3Step 3: Return the count.
solution.py8 lines
1# Full working Python code
2
3def hammingWeight(n):
4    count = 0
5    while n:
6        count += n & 1
7        n >>= 1
8    return count

Complexity note: The time complexity is O(log n) because we are effectively dividing n by 2 each time (right shift), which reduces the number of bits we need to check.

  • 1Understanding bit manipulation can lead to more efficient solutions.
  • 2Counting bits directly avoids unnecessary conversions and is faster.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.