Number of 1 Bits

Easy Bit Manipulation

Problem

Given an unsigned 32-bit integer n, return the count of 1-bits (the Hamming weight).

Example 1 Input: n = 11 Output: 3 Explain: 0b1011 has three 1s
Example 2 Input: n = 128 Output: 1
Example 3 Input: n = 4294967293 Output: 31

Constraints

Approach — Core Patterns

This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: see the walkthrough below.

Solution code

Python

class Solution:
    def hammingWeight(self, n):
        return bin(n & 0xFFFFFFFF).count('1')

Java

class Solution {
    public int hammingWeight(int n) {
        int count = 0;
        while (n != 0) {
            n &= (n - 1);
            count++;
        }
        return count;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Number of 1 Bits interactively → ← All solutions