Back to DSA

Number of 1 Bits

easy
Acceptance: 62%
Bit Manipulation

Given the binary form of a positive integer, count how many bits are set to 1. This is sometimes called the Hamming weight of the number.

Examples

Example 1:
Input:n = 7 (111)
Output:3
Example 2:
Input:n = 16 (10000)
Output:1

Hints

00:00
public class Solution {
    public int hammingWeight(int n) {
        int count = 0;
        while (n != 0) {
            count++;
            n &= (n - 1);
        }
        return count;
    }
}
Time complexityO(k)
Space complexityO(1)