Command Palette
Search for a command to run...
Problem 34.2 · Bit ManipulationEasy
What it teaches: Brian Kernighan's loop: n & (n − 1) removes one set bit per step.
Practise it on judges as “Number of 1 Bits”.
The problem
Return the number of set bits in the binary representation of a positive integer n.
Example 1
Input: n = 11
Output: 3
1011.
Constraints
Pattern clues in the wording
These clues point to Bit Manipulation: Use XOR, AND, OR and shifts to test, set and cancel bits, often in O(1) space.
Stuck? Take one hint at a time
Solution.java · starterclass Solution {
public int hammingWeight(int n) {
return 0;
}
}
Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.
Test cases
| # | Input | Expected |
|---|
| 1 | n = 11 | 3 |
| 2 | n = 128 | 1 |
| 3 | n = 2147483645 | 30 |