Submissions disabled: This deployment is running in read-only mode for safety. Code execution is not available here.
← Back to all problems
Easy

Number of 1 Bits

Updated Jan 31, 2026

Problem

Write a function that takes the binary representation of a positive integer and returns the number of set bits it has (also known as the Hamming weight).

Constraints

1 <= n <= 2^31 - 1

Follow Up

If this function is called many times, how would you optimize it?

Examples

Example 1

Input: n = 11 (binary: 1011)
Output: 3
The input binary string 1011 has a total of three set bits.

Example 2

Input: n = 128 (binary: 10000000)
Output: 1

Example 3

Input: n = 2147483645
Output: 30

Function Signature

def hammingWeight(self, n: int) -> int

How to Submit

Implement a Solution class with a hammingWeight method.

Your method will be called with the input parameters and should return the answer.