Number of 1 Bits — Solution in Python, Java & C++
Number of 1 Bits solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Number of 1 Bits is an easy coding problem on bit manipulation and divide and conquer, asked in Amazon, Google, Microsoft and Apple interviews.
- Difficulty: Easy
- Topics: Bit Manipulation, Divide and Conquer
- Asked at: Amazon, Google, Microsoft, Apple
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Write a function that takes a non-negative integer n and returns the number of 1 bits in its binary representation — its Hamming weight.
Example 1
Input: n = 11
Output: 3
Explanation: 11 is 1011 in binary.
Example 2
Input: n = 128
Output: 1
Example 3
Input: n = 0
Output: 0
Constraints
0 <= n <= 2147483647
Follow-up: If this function is called many times, how would you optimise it?
Hints for Number of 1 Bits
Hint 1
Test the lowest bit with
n & 1, then shift right, until nothing is left.Hint 2
n & (n - 1)clears the lowest set bit, so a loop over that runs once per 1 bit instead of once per bit.Hint 3
Use a logical (unsigned) shift so the loop terminates.
How to solve Number of 1 Bits
n & (n - 1) clears the lowest set bit; loop until zero and count the iterations.
Approach
- While
n != 0:n &= n - 1, increment the count. - Return the count.
Why it works
Subtracting one borrows through the trailing zeros and flips the lowest set bit, so the AND removes exactly that bit each iteration.
Complexity
- Time —
O(popcount) - Space —
O(1)
Pitfalls
- In a signed 32-bit language use a logical shift if you shift instead, or the loop never ends for negatives.
Reference solution
Python
def hammingWeight(n: int) -> int:
count = 0
while n:
n &= n - 1
count += 1
return countJava
public static int hammingWeight(int n) {
int count = 0;
int v = n;
while (v != 0) {
v &= v - 1;
count++;
}
return count;
}C++
int hammingWeight(int n) {
unsigned int v = (unsigned int) n;
int count = 0;
while (v) {
v &= v - 1;
count++;
}
return count;
}JavaScript
var hammingWeight = function(n) {
let count = 0;
let v = n >>> 0;
while (v > 0) {
v &= v - 1;
count++;
}
return count;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 146 bit manipulation problems · the whole catalogue
Learn the technique: Bit Manipulation