LeetCode 191: Number Of 1 Bits — Step-by-Step Visual Trace


Easy — Bit Manipulation | Math

The Problem

Given a positive integer n, count and return the number of set bits (1s) in its binary representation.

Approach

Use bit manipulation to check each bit position by performing bitwise AND with 1 to detect if the least significant bit is set, then right shift to examine the next bit. Continue until all bits are processed.

Time: O(log n) · Space: O(1)

Code

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

Watch It Run

Try it yourself: Open TraceLit and step through every line.


Built with TraceLit — the visual algorithm tracer for LeetCode practice.


Comments