L191. Number of 1 Bits

Math

Problem:

Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).

Example 1:

Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

Solution:

public int hammingWeight(int n) {
    if(n == 0) return 0;
    int count = 0;
    for(int i = 0; i < 32; i++){
        if(n == 0) break;
        if(((n >> i) & 1) != 0) count ++;
    }
    return count;
}

Last updated

Was this helpful?