Number of 1 Bits — LeetCode 191 Python Solution

EasyBit ManipulationDivide and Conquer
Problem
#191
Reading time
2 min

The problem

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).

Python solution

Python
class Solution:
    def hammingWeight(self, n: int) -> int:
        ans = 0
        while n:
            n &= n - 1
            ans += 1
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 191. Number of 1 Bits is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

On study lists

This problem is on Blind 75, NeetCode 150 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 191. Number of 1 Bits?
LeetCode 191. Number of 1 Bits is rated Easy on LeetCode.
What is the time complexity of LeetCode 191. Number of 1 Bits?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 191. Number of 1 Bits?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 191. Number of 1 Bits cover?
LeetCode 191. Number of 1 Bits is tagged Bit Manipulation and Divide and Conquer on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview