Number of 1 Bits
Easy
Topics
Given a non-negative integer n, return the number of set bits (1s) in its binary representation (its Hamming weight).
Example 1
The answer is simply how many cells hold a
1 — 3 here. The trick worth knowing is n & (n-1), which clears the lowest set bit, so the loop runs once per set bit rather than 32 times.Cells are the binary expansion, most significant bit on the left; the small numbers are bit positions.
Input: n = 11 Output: 3 Explanation: 11 = 1011 in binary.
Example 2
Input: n = 128 Output: 1
Constraints
- 0 <= n <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
The identity n & (n - 1) clears the lowest set bit. Repeatedly applying it counts exactly as many iterations as there are set bits.
Approach
- Initialize a counter to 0.
- While
nis non-zero, don &= n - 1and increment the counter. - Return the counter.
Walkthrough
n = 11 (1011)
1011 & 1010 = 1010 (count 1)
1010 & 1001 = 1000 (count 2)
1000 & 0111 = 0000 (count 3) -> answer 3Complexity
- Time — O(bits set): one iteration per set bit (at most 32).
- Space — O(1): a single counter.
Common Pitfalls
- Count the ones in the binary representation. Counting the character
1in the decimal string is a different question entirely and returns 2 instead of 3 for 11. n & (n - 1)clears the lowest set bit, so looping on that runs once per set bit rather than once per bit width. Worth naming as the answer when the interviewer asks for it without a built-in.
Full Solution — all languages
class Solution:
def hammingWeight(self, n):
return bin(n).count('1')import java.util.*;
class Solution {
public int hammingWeight(int n) {
return Integer.bitCount(n);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int hammingWeight(int n) {
int c = 0;
while (n) {
c += n & 1;
n >>= 1;
}
return c;
}
};/**
* @param {number} n
* @return {number}
*/ var hammingWeight = function(n) {
let c = 0;
while (n) {
c += n & 1;
n >>>= 1;
}
return c;
};