Example: Number of 1 Bits - rFronteddu/general_wiki GitHub Wiki

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).

class Solution {
    public int hammingWeight(int n) {
        // without toUnsignedLong(n), when n is negative the leftmost bit is 1. 
        // shifting does not remove this 1 thus leading to an infinite loop

        var i = Integer.toUnsignedLong(n);
        var count = 0;
    
        while (i > 0) {
            count += i & 1; // 1 if the least significant bit is 1, 0 otherwise
            i >>= 1; // shift right to process next bit
        }
        return count;
    }
}