Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on bit manipulation fundamentals.
Given a positive integer n, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight).
Example 1:
Input: n = 11
Output: 3
Explanation:
The input binary string 1011 has a total of three set bits.
Example 2:
Input: n = 128
Output: 1
Explanation:
The input binary string 10000000 has a total of one set bit.
Example 3:
Input: n = 2147483645
Output: 30
Explanation:
The input binary string 1111111111111111111111111111101 has a total of thirty set bits.
Constraints:
1 <= n <= 231 - 1Problem summary: Given a positive integer n, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight).
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Bit Manipulation
11
128
2147483645
reverse-bits)power-of-two)counting-bits)binary-watch)hamming-distance)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #191: Number of 1 Bits
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int ans = 0;
while (n != 0) {
n &= n - 1;
++ans;
}
return ans;
}
}
// Accepted solution for LeetCode #191: Number of 1 Bits
func hammingWeight(num uint32) int {
ans := 0
for num != 0 {
num &= num - 1
ans++
}
return ans
}
# Accepted solution for LeetCode #191: Number of 1 Bits
class Solution:
def hammingWeight(self, n: int) -> int:
ans = 0
while n:
n &= n - 1
ans += 1
return ans
// Accepted solution for LeetCode #191: Number of 1 Bits
impl Solution {
pub fn hammingWeight(n: u32) -> i32 {
n.count_ones() as i32
}
}
// Accepted solution for LeetCode #191: Number of 1 Bits
function hammingWeight(n: number): number {
let ans: number = 0;
while (n !== 0) {
ans++;
n &= n - 1;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Sort the array in O(n log n), then scan for the missing or unique element by comparing adjacent pairs. Sorting requires O(n) auxiliary space (or O(1) with in-place sort but O(n log n) time remains). The sort step dominates.
Bitwise operations (AND, OR, XOR, shifts) are O(1) per operation on fixed-width integers. A single pass through the input with bit operations gives O(n) time. The key insight: XOR of a number with itself is 0, which eliminates duplicates without extra space.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.