← Math

Hamming Weight

Easy
Python
def hamming_weight(n):
    count=0
    while n:
        count+=n&1; n>>=1
    return count
Java
public int hammingWeight(int n){
    int count=0;
    while(n!=0){
        count+=n&1; n>>>=1;
    } return count;
}

Key Insight

Python 'while n' — 0 is falsy. Java n!=0 explicit. >>> for unsigned shift.

Python → Java Differences

  • 'while n' vs n!=0
  • Java >>> unsigned shift vs >>
  • Bit counting identical
Python
def hamming_weight(n):
    count=0
    while n:
        count+=n&1; n>>=1
    return count
Java
public int hammingWeight(int n){
    int count=0;
    while(n!=0){
        count+=n&1; n>>>=1;
    } return count;
}

Algorithm Steps

1. Check last bit n&1
2. Right shift
3. Count