Algo-Sim › Matrix & Bit Manipulation

Number of 1 Bits

Easy · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input

Count the set bits of n. n & (n − 1) clears the lowest 1 bit, so the loop runs once per set bit.

Problem

Given a non-negative integer n, return how many 1 bits its binary form has (its Hamming weight).

Constraints

Edge cases to test

Follow-up questions

What if you call it millions of times?
Use a 256-entry lookup table per byte, or the hardware popcount (Integer.bitCount, __builtin_popcount).
Why use >>> in Java?
>> copies the sign bit, so a negative n never reaches 0. n & (n − 1) avoids the shift entirely.

Solution

Java

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

Python

def hamming_weight(n):
    count = 0
    while n != 0:
        n &= n - 1
        count += 1
    return count

C++

#include <bits/stdc++.h>
using namespace std;

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

More Matrix & Bit Manipulation problems