Leetcode #191: Number of 1 Bits
In this guide, we solve Leetcode #191 Number of 1 Bits in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given a positive integer n, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight). Example 1: Input: n = 11 Output: 3 Explanation: The input binary string 1011 has a total of three set bits.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Bit Manipulation, Divide and Conquer
Intuition
The problem structure lets us track state with bitwise operations.
Bit operations are constant time and avoid extra memory.
Approach
Apply XOR/AND/OR and shifts to maintain the required invariant.
Aggregate the result in a single pass.
Steps:
- Identify a bitwise invariant.
- Combine values with bit operations.
- Return the aggregated result.
Python Solution
class Solution:
def hammingWeight(self, n: int) -> int:
ans = 0
while n:
n &= n - 1
ans += 1
return ans
Complexity
The time complexity is O(n). The space complexity is O(1).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.