Algo-Sim › Matrix & Bit Manipulation
Number of 1 Bits
Easy · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input
Count the set bits of n. n & (n − 1) clears the lowest 1 bit, so the loop runs once per set bit.
Problem
Given a non-negative integer n, return how many 1 bits its binary form has (its Hamming weight).
Constraints
- 1 ≤ n ≤ 2³¹ − 1
- Follow-up: called many times, can each call cost one step per set bit?
Edge cases to test
- n = 0
- All 32 bits set
- Only the top bit set (sign in Java)
Follow-up questions
- What if you call it millions of times?
- Use a 256-entry lookup table per byte, or the hardware popcount (
Integer.bitCount,__builtin_popcount). - Why use
>>>in Java? >>copies the sign bit, so a negative n never reaches 0.n & (n − 1)avoids the shift entirely.
Solution
Java
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
n &= n - 1;
count++;
}
return count;
}Python
def hamming_weight(n):
count = 0
while n != 0:
n &= n - 1
count += 1
return countC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while (n != 0) {
n &= n - 1;
count++;
}
return count;
}
};
More Matrix & Bit Manipulation problems
- Rotate Image (Medium)
- Spiral Matrix (Medium)
- Set Matrix Zeroes (Medium)
- Search a 2D Matrix (Medium)
- Search a 2D Matrix II (Medium)
- Valid Sudoku (Medium)
- Single Number (Easy)
- Single Number II (Medium)
- Single Number III (Medium)
- Counting Bits (Easy)
- Reverse Bits (Easy)
- Missing Number (Easy)
- Sum of Two Integers (Medium)
- Power of Two (Easy)