Back to DSA
Number of 1 Bits
easyGiven 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:
1Hints
public class Solution {
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
count++;
n &= (n - 1);
}
return count;
}
}Time complexity
O(k)Space complexity
O(1)