def hamming_weight(n):
count=0
while n:
count+=n&1; n>>=1
return count
public int hammingWeight(int n){
int count=0;
while(n!=0){
count+=n&1; n>>>=1;
} return count;
}
Python 'while n' — 0 is falsy. Java n!=0 explicit. >>> for unsigned shift.
def hamming_weight(n):
count=0
while n:
count+=n&1; n>>=1
return count
public int hammingWeight(int n){
int count=0;
while(n!=0){
count+=n&1; n>>>=1;
} return count;
}
1. Check last bit n&1 2. Right shift 3. Count