Hi👋SpeedAlgo • Deliberate Practice & Cognitive Ergonomics for Software Engineers

An interactive algorithm mastery and technical interview preparation platform published by Hi👋WebEnterprise. Built for senior and staff software engineers preparing for rigorous coding screens at top tech companies (FAANG/MAMAA).

13 Core Algorithmic Patterns & 225 Practice Problems

  • 1. Two Pointers (16 Paradigms, 43 Problems): Opposite ends, sorted pair sums, palindrome verification, trapping rain water, 3Sum, container with most water — includes the Sliding Window and Fast & Slow Pointers paradigms (contiguous subarray invariants, longest substrings, Floyd's cycle detection, linked list middle).
  • 2. Binary Search (9 Paradigms, 14 Problems): Monotonic predicate partitioning (feasible(x)), boundary search, rotated sorted arrays, square roots, minimum ship capacity, median of two sorted arrays, matrix median on value range.
  • 3. Bit Manipulation (5 Paradigms, 11 Problems): Counting set bits, XOR cancellation, bit reversal, bitmask pairing, maximum XOR with a bitwise trie.
  • 4. Math & Geometry (8 Paradigms, 14 Problems): Sieve of Eratosthenes, integer/roman conversions, modular arithmetic, geometric simulation.
  • 5. Tree/Graph Depth-First Search (15 Paradigms, 24 Problems): Path sums, lowest common ancestor, tree diameter, validating BSTs, tree DP (House Robber III, Binary Tree Cameras).
  • 6. Tree/Graph Breadth-First Search (5 Paradigms, 12 Problems): Level-order traversals, shortest path in unweighted graphs, zig-zag traversals, rotting oranges, word ladders.
  • 7. Graphs (12 Paradigms, 22 Problems): Topological sort, cycle detection, Dijkstra's algorithm, bipartite graph validation, network delay.
  • 8. Backtracking (6 Paradigms, 14 Problems): Subsets, permutations, combinations, constraint satisfaction, pruning, N-Queens, Sudoku solver.
  • 9. Dynamic Programming (13 Paradigms, 28 Problems): Memoization vs tabulation, 0/1 knapsack, unbounded knapsack, coin change, edit distance, longest common subsequence.
  • 10. Heap / Priority Queue (9 Paradigms, 11 Problems): Running medians, top-k elements, interval scheduling, IPO, k-way merges.
  • 11. Advanced Data Structures (7 Paradigms, 17 Problems): Trie (prefix tree), Union-Find (Disjoint Set Union), LRU Cache, LFU Cache, range-sum queries with updates.
  • 12. Stack (5 Paradigms, 9 Problems): Next greater element, largest rectangle in histogram, remove k digits, decode string, min stack.
  • 13. Intervals & Greedy (2 Paradigms, 6 Problems): Merge intervals, interval scheduling, meeting rooms by sweep line, jump game.

4-Stage Deliberate Practice Framework

  1. Stage 1 (Compare & Learn): Read the pattern's mental model, loop invariant and Big-O proof, compare the pattern's template with the problem's solution side by side, and use the step-by-step debugger. The solution can also be shown in C#, Java, TypeScript, C++, Go or Rust for almost every problem.
  2. Stage 2 (Active Recall): Rebuild the solution from memory in a code editor, with an invariant checklist and optional progressive hints, and check it against a judged test suite.
  3. Stage 3 (AI Interview Coach, coming soon): A mock-interview stage still in development; for now, students go straight from Stage 2 to Stage 4.
  4. Stage 4 (Solve on Your Own): Solve a new problem on your own against a 15-minute timer; your code is graded against a test suite. Python and TypeScript run in your browser and C# runs on our server (design problems grade in Python and TypeScript).

Equipped with a spaced-repetition review hub on a fixed 7-step schedule (1 day up to 90 days), a two-pane Studio workspace, and study notes.

Pricing, Access & Commercial Terms

  • Core Curriculum: 100% Free. No credit card required.
  • Coins: New accounts get 40 free coins once, the daily claim adds +20 coins once a day, and inviting a friend earns you +25 coins when they complete their first practice step. These are the only ways to earn coins.
  • AI Coach: Each AI coach question costs 1-5 coins, priced by the server according to its size.
  • BYOK (Bring Your Own Key): AI coaching is free with your own Google Gemini, OpenAI or OpenRouter API key (BYOK).
  • Extras: Coins also unlock extras for 24 hours: a Recall hint level (1 coin), a Solve solution reveal (2), a LeetCode problem card's solutions (1) and a pattern's extra canonical problems (1).
  • Payments & Refunds: Nothing on the site is sold for money: coins can only be earned, never bought. There are no subscriptions or charges, so there is nothing to refund.
  • Platform Operator: Hi👋WebEnterprise. Support & policies at hispeedalgo.com.
Skip to main content
Hi👋SpeedAlgo

Invariant-First Algorithmic Mastery

Arena
238Items
Theory Context•Bit Manipulation
EasyLC 191

Number of 1 Bits (LeetCode 191)

Target Frequency:MetaAmazonGoogleApple

Given a positive integer n, count how many bits equal 1 appear in its binary form — this count is known as the number's Hamming weight.

A set bit refers to a bit in the binary representation of a number that is equal to 1.

Worked Examples

Example 1
Input:n = 11
Output:3
Explanation: n = 11 is 1011 in binary, which contains three 1-bits.
Example 2
Input:n = 128
Output:1
Explanation: n = 128 is 10000000 in binary, which contains only one 1-bit.
Example 3
Input:n = 2147483645
Output:30
Explanation: n = 2147483645 is 1111111111111111111111111111101 in binary, which contains thirty 1-bits.

⚖️Formal Constraints & Bounds

  • 1 <= n <= 231 - 1

Deep-Dive & Conceptual Insights

Core Insight

Subtracting 1 from n flips all bits up to and including the lowest set bit. Therefore, n & (n - 1) resets the least significant 1-bit to 0 in a single operation, eliminating the need to shift through 32 full bits.

Real-World Scenario & Production Applications

Network packet error detection (parity checking), population count (popcount) in cryptography & hash functions, bitboard piece evaluation in chess engines.

Step-by-Step Execution Trace Table

IterationCurrent n (Binary)n - 1 (Binary)n & (n - 1)Set Bit Count
111 (1011₂)10 (1010₂)10 (1010₂)1
210 (1010₂)9 (1001₂)8 (1000₂)2
38 (1000₂)7 (0111₂)0 (0000₂)3 (Terminates n = 0)
Worked on Paper

The Math, Step by Step

1. The number the code counts

The Hamming weight of nnn is the number of 1 bits in its binary form. The code does not look at every bit. It removes one 1 bit per round, and counts the rounds until nnn is 0.

2. What n & (n - 1) does to one number

Write nnn in binary. Its lowest 1 bit has some number k≥0k \ge 0k≥0 of 0 bits to its right. Call everything to the left of that 1 bit the prefix XXX:

n=X 1 0⋯0⏟kn = X\,1\,\underbrace{0 \cdots 0}_{k}n=X1k0⋯0​​

Subtracting 1 borrows from the lowest 1 bit. That bit becomes 0, and the kkk zeros to its right become 1s. The prefix XXX does not change:

n−1=X 0 1⋯1⏟kn - 1 = X\,0\,\underbrace{1 \cdots 1}_{k}n−1=X0k1⋯1​​

& keeps a bit only where both numbers have a 1:

Part of the bitsIn nnnIn n−1n - 1n−1In n & (n - 1)
the prefix XXXXXXXXXXXX
the lowest 1 bit100
the kkk bits to its rightall 0all 1all 0

So n & (n - 1) is nnn with its lowest 1 bit cleared, and every other bit unchanged. This is Kernighan's bit trick.

3. Why the loop runs once per 1 bit

Each round clears exactly one 1 bit and changes no other bit. So after www rounds, where www is the Hamming weight, all 1 bits are gone and nnn is 0. The loop while n > 0 then stops, and count equals www.

The loop runs www times, not once per bit position. For n=128n = 128n=128, which has 8 bit positions, it runs only once.

4. The stopping condition

The loop stops at n=0n = 0n=0, which has no 1 bit. For n=0n = 0n=0 the rule of part 2 does not apply, because 0 has no lowest 1 bit. The loop never computes 0 & (0 - 1), because while n > 0 checks first. The problem guarantees n≥1n \ge 1n≥1, so the loop runs at least once.

The input is at least 1 and at most 231−12^{31} - 1231−1, so nnn is never negative. If it were, while n > 0 would be false at once, and the code would return 0.

5. Example 1 by hand

n = 11, which is 1011 in binary.

Roundnn - 1n & (n - 1)count
11011101010101
21010100110002
31000011100003

Each row clears the lowest 1 bit: bit 0, then bit 1, then bit 3. After round 3, n is 0, so the loop stops. The code returns 3, the expected output.

6. Example 2 by hand

n = 128, which is 10000000 in binary. Then n - 1 = 127 is 01111111, and n & (n - 1) is 0. The loop runs once, and the code returns 1, the expected output.

7. From the math to the code
MathIn hammingWeight
no rounds yetcount = 0
stop when no 1 bit is leftwhile n > 0:
clear the lowest 1 bitn &= (n - 1)
one 1 bit removedcount += 1
the Hamming weightreturn count

The loop runs once per 1 bit, at most 31 times for this input range. So the code takes O(w)O(w)O(w) time, where www is the number of 1 bits, and O(1)O(1)O(1) space.

Code Shape
Archetype Code Shape
Python
1count = 0
2while n > 0:
3 n &= (n - 1)
4 count += 1
5return count

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

The line n &= (n - 1) clears one bit of n, and at first it is not clear which bit or why. A physical picture shows the mechanism step by step.

💡 The Analogy: A Row of Light Switches

Picture your number as a row of light switches, ON (1) or OFF (0). You want to count how many switches are ON, but instead of checking all 32 switches one by one, you want a shortcut that only takes as many steps as there are ON switches.

  1. Borrowing (n - 1): Subtracting 1 finds the rightmost ON switch, flips it OFF, and flips every switch to its right ON (like borrowing in grade-school subtraction ripples through the digits). Everything to the left of that switch is untouched.
  2. Cancelling (n & (n - 1)): Now AND the borrowed row against the original row. A switch stays ON after the AND only if it was ON in both rows. The rightmost ON switch is OFF in the borrowed row, so it ends up OFF. Everything the borrow flipped ON to its right was already OFF in the original row, so those end up OFF too. Every switch to the left never changed, so it keeps its value. Net effect: exactly one switch — the rightmost ON one — gets cleared, and nothing else moves.
🔑 The Key Idea in the Code

Because each pass clears exactly one ON switch, the loop runs exactly K times — the number of 1 bits — never the full 32, no matter how large n is.

  • Fixed 32-iteration loop vs Kernighan's optimization: Looping 32 times does redundant work for sparse bitmasks. n &= (n - 1) terminates as soon as all set bits are cleared.

  • Signed infinite loop in typed languages: In C++/Java, n >>= 1 on signed negative values fills the MSB with 1s indefinitely. Use unsigned types (uint32_t) or logical shift.

  • Using modulo % 2 and division // 2: Modulo and division require ALU division circuits; bitwise n & 1 and n >>= 1 are single-cycle bitwise instructions.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Counting binary 1-bits, bit population count, register parity checks.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: count plus the set bits still in n always equals the set bits of the original n. The loop ends when n is 0, so count is then the answer.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • A shift loop (count += n & 1; n >>= 1) runs once per bit position up to the highest 1, up to 31 rounds here; Kernighan's loop runs once per set bit.

  • while n > 0, not a fixed for _ in range(32): the loop must stop once the last set bit is cleared, or count keeps growing (n = 11 would give 32, not 3).

  • return n > 0 and (n & (n - 1)) == 0 in is_power_of_two: 0 & -1 is also 0, so without n > 0 the answer for 0 is True.

The 60-Second Interview Pitch

Say this out loud before you type a single line

This is Kernighan's Bit Trick. I keep count = 0 and, while n is above zero, run n &= (n - 1) and add one to count. Subtracting one turns the lowest set bit into a zero and the zeros below it into ones, so the AND removes exactly that bit and keeps every higher bit. That means count plus the bits left in n always equals the answer, and when n reaches zero, count is it. The loop condition is the part to get right: it stops as soon as the last set bit is gone, instead of walking all 32 positions. Time is O(K) for K set bits, at most 31 here, and space is O(1).

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(K), K = number of set bits (<= 32)

Look at the execution steps: each round of while n > 0 runs n &= (n - 1), which removes one set bit, so the loop runs exactly K times, where K is the number of set bits.

SPACE COMPLEXITY

O(1)

Look at memory allocations: Call stack uses O(1) Iterative. Single integer counter register.

Formal Recurrence Relation

T(K)=K rounds=O(K)T(K) = K \text{ rounds} = O(K)T(K)=K rounds=O(K)

Derivation Progression

Rounds

1 set bit removed per round ⟹ K rounds

Each n &= (n - 1) removes one set bit, so after K rounds n is 0.

Counter Increment

count += 1 per set bit

Counts exactly the number of set bits.

Loop Exit

while n > 0 fails at n = 0

The loop stops right after the last set bit is cleared; no round is spent on a zero bit.

Variable Definitions

KKK

Number of set bits in n (at most 31, since LC 191 has n ≤ 2^31 - 1)

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(1) CPU registers

🟢 Output Space

O(1) Set bit count integer

Boundary Best / Worst Cases

Best Case

O(1)O(1)O(1): n a power of two (1 round).

Average Case

O(K)O(K)O(K): one round per set bit.

Worst Case

O(31)O(31)O(31) = O(1)O(1)O(1): n = 2^{31} - 1 (31 rounds).

Pointer Invariant Transition Progression

Pointer Invariant Transition Progression
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

When I look at this problem statement, the trigger phrase is "number of '1' bits" (also known as Hamming Weight or Population Count / popcount). A loop over every bit position works, but the count only needs one step per set bit: Kernighan's Bit Trick, n & (n - 1). At scale the same count runs word by word over large bitmaps, where each sparse word finishes in a few rounds.

CONSTRAINTS & BOUNDS

LeetCode gives 1≤n≤231−11 \le n \le 2^{31} - 11≤n≤231−1, so n has at most 31 set bits and the loop runs at most 31 times. It stops as soon as n reaches 0.

FAANG PRODUCTION TRAPS & EDGE CASES

If an API can pass a negative value (a signed 32-bit register holding unsigned data), mask it to 32 bits first: while n > 0 returns 0 at once for a negative number, and while n: never ends on a negative Python int. Edge cases: n=1n = 1n=1 (1 round) and n=231−1n = 2^{31} - 1n=231−1 (31 rounds).

Theory Context•Bit Manipulation
EasyLC 191

Number of 1 Bits (LeetCode 191)

Target Frequency:MetaAmazonGoogleApple

Given a positive integer n, count how many bits equal 1 appear in its binary form — this count is known as the number's Hamming weight.

A set bit refers to a bit in the binary representation of a number that is equal to 1.

Worked Examples

Example 1
Input:n = 11
Output:3
Explanation: n = 11 is 1011 in binary, which contains three 1-bits.
Example 2
Input:n = 128
Output:1
Explanation: n = 128 is 10000000 in binary, which contains only one 1-bit.
Example 3
Input:n = 2147483645
Output:30
Explanation: n = 2147483645 is 1111111111111111111111111111101 in binary, which contains thirty 1-bits.

⚖️Formal Constraints & Bounds

  • 1 <= n <= 231 - 1

Deep-Dive & Conceptual Insights

Core Insight

Subtracting 1 from n flips all bits up to and including the lowest set bit. Therefore, n & (n - 1) resets the least significant 1-bit to 0 in a single operation, eliminating the need to shift through 32 full bits.

Real-World Scenario & Production Applications

Network packet error detection (parity checking), population count (popcount) in cryptography & hash functions, bitboard piece evaluation in chess engines.

Step-by-Step Execution Trace Table

IterationCurrent n (Binary)n - 1 (Binary)n & (n - 1)Set Bit Count
111 (1011₂)10 (1010₂)10 (1010₂)1
210 (1010₂)9 (1001₂)8 (1000₂)2
38 (1000₂)7 (0111₂)0 (0000₂)3 (Terminates n = 0)
Worked on Paper

The Math, Step by Step

1. The number the code counts

The Hamming weight of nnn is the number of 1 bits in its binary form. The code does not look at every bit. It removes one 1 bit per round, and counts the rounds until nnn is 0.

2. What n & (n - 1) does to one number

Write nnn in binary. Its lowest 1 bit has some number k≥0k \ge 0k≥0 of 0 bits to its right. Call everything to the left of that 1 bit the prefix XXX:

n=X 1 0⋯0⏟kn = X\,1\,\underbrace{0 \cdots 0}_{k}n=X1k0⋯0​​

Subtracting 1 borrows from the lowest 1 bit. That bit becomes 0, and the kkk zeros to its right become 1s. The prefix XXX does not change:

n−1=X 0 1⋯1⏟kn - 1 = X\,0\,\underbrace{1 \cdots 1}_{k}n−1=X0k1⋯1​​

& keeps a bit only where both numbers have a 1:

Part of the bitsIn nnnIn n−1n - 1n−1In n & (n - 1)
the prefix XXXXXXXXXXXX
the lowest 1 bit100
the kkk bits to its rightall 0all 1all 0

So n & (n - 1) is nnn with its lowest 1 bit cleared, and every other bit unchanged. This is Kernighan's bit trick.

3. Why the loop runs once per 1 bit

Each round clears exactly one 1 bit and changes no other bit. So after www rounds, where www is the Hamming weight, all 1 bits are gone and nnn is 0. The loop while n > 0 then stops, and count equals www.

The loop runs www times, not once per bit position. For n=128n = 128n=128, which has 8 bit positions, it runs only once.

4. The stopping condition

The loop stops at n=0n = 0n=0, which has no 1 bit. For n=0n = 0n=0 the rule of part 2 does not apply, because 0 has no lowest 1 bit. The loop never computes 0 & (0 - 1), because while n > 0 checks first. The problem guarantees n≥1n \ge 1n≥1, so the loop runs at least once.

The input is at least 1 and at most 231−12^{31} - 1231−1, so nnn is never negative. If it were, while n > 0 would be false at once, and the code would return 0.

5. Example 1 by hand

n = 11, which is 1011 in binary.

Roundnn - 1n & (n - 1)count
11011101010101
21010100110002
31000011100003

Each row clears the lowest 1 bit: bit 0, then bit 1, then bit 3. After round 3, n is 0, so the loop stops. The code returns 3, the expected output.

6. Example 2 by hand

n = 128, which is 10000000 in binary. Then n - 1 = 127 is 01111111, and n & (n - 1) is 0. The loop runs once, and the code returns 1, the expected output.

7. From the math to the code
MathIn hammingWeight
no rounds yetcount = 0
stop when no 1 bit is leftwhile n > 0:
clear the lowest 1 bitn &= (n - 1)
one 1 bit removedcount += 1
the Hamming weightreturn count

The loop runs once per 1 bit, at most 31 times for this input range. So the code takes O(w)O(w)O(w) time, where www is the number of 1 bits, and O(1)O(1)O(1) space.

Code Shape
Archetype Code Shape
Python
1count = 0
2while n > 0:
3 n &= (n - 1)
4 count += 1
5return count

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

The line n &= (n - 1) clears one bit of n, and at first it is not clear which bit or why. A physical picture shows the mechanism step by step.

💡 The Analogy: A Row of Light Switches

Picture your number as a row of light switches, ON (1) or OFF (0). You want to count how many switches are ON, but instead of checking all 32 switches one by one, you want a shortcut that only takes as many steps as there are ON switches.

  1. Borrowing (n - 1): Subtracting 1 finds the rightmost ON switch, flips it OFF, and flips every switch to its right ON (like borrowing in grade-school subtraction ripples through the digits). Everything to the left of that switch is untouched.
  2. Cancelling (n & (n - 1)): Now AND the borrowed row against the original row. A switch stays ON after the AND only if it was ON in both rows. The rightmost ON switch is OFF in the borrowed row, so it ends up OFF. Everything the borrow flipped ON to its right was already OFF in the original row, so those end up OFF too. Every switch to the left never changed, so it keeps its value. Net effect: exactly one switch — the rightmost ON one — gets cleared, and nothing else moves.
🔑 The Key Idea in the Code

Because each pass clears exactly one ON switch, the loop runs exactly K times — the number of 1 bits — never the full 32, no matter how large n is.

  • Fixed 32-iteration loop vs Kernighan's optimization: Looping 32 times does redundant work for sparse bitmasks. n &= (n - 1) terminates as soon as all set bits are cleared.

  • Signed infinite loop in typed languages: In C++/Java, n >>= 1 on signed negative values fills the MSB with 1s indefinitely. Use unsigned types (uint32_t) or logical shift.

  • Using modulo % 2 and division // 2: Modulo and division require ALU division circuits; bitwise n & 1 and n >>= 1 are single-cycle bitwise instructions.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Counting binary 1-bits, bit population count, register parity checks.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: count plus the set bits still in n always equals the set bits of the original n. The loop ends when n is 0, so count is then the answer.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • A shift loop (count += n & 1; n >>= 1) runs once per bit position up to the highest 1, up to 31 rounds here; Kernighan's loop runs once per set bit.

  • while n > 0, not a fixed for _ in range(32): the loop must stop once the last set bit is cleared, or count keeps growing (n = 11 would give 32, not 3).

  • return n > 0 and (n & (n - 1)) == 0 in is_power_of_two: 0 & -1 is also 0, so without n > 0 the answer for 0 is True.

The 60-Second Interview Pitch

Say this out loud before you type a single line

This is Kernighan's Bit Trick. I keep count = 0 and, while n is above zero, run n &= (n - 1) and add one to count. Subtracting one turns the lowest set bit into a zero and the zeros below it into ones, so the AND removes exactly that bit and keeps every higher bit. That means count plus the bits left in n always equals the answer, and when n reaches zero, count is it. The loop condition is the part to get right: it stops as soon as the last set bit is gone, instead of walking all 32 positions. Time is O(K) for K set bits, at most 31 here, and space is O(1).

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(K), K = number of set bits (<= 32)

Look at the execution steps: each round of while n > 0 runs n &= (n - 1), which removes one set bit, so the loop runs exactly K times, where K is the number of set bits.

SPACE COMPLEXITY

O(1)

Look at memory allocations: Call stack uses O(1) Iterative. Single integer counter register.

Formal Recurrence Relation

T(K)=K rounds=O(K)T(K) = K \text{ rounds} = O(K)T(K)=K rounds=O(K)

Derivation Progression

Rounds

1 set bit removed per round ⟹ K rounds

Each n &= (n - 1) removes one set bit, so after K rounds n is 0.

Counter Increment

count += 1 per set bit

Counts exactly the number of set bits.

Loop Exit

while n > 0 fails at n = 0

The loop stops right after the last set bit is cleared; no round is spent on a zero bit.

Variable Definitions

KKK

Number of set bits in n (at most 31, since LC 191 has n ≤ 2^31 - 1)

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(1) CPU registers

🟢 Output Space

O(1) Set bit count integer

Boundary Best / Worst Cases

Best Case

O(1)O(1)O(1): n a power of two (1 round).

Average Case

O(K)O(K)O(K): one round per set bit.

Worst Case

O(31)O(31)O(31) = O(1)O(1)O(1): n = 2^{31} - 1 (31 rounds).

Pointer Invariant Transition Progression

Pointer Invariant Transition Progression
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

When I look at this problem statement, the trigger phrase is "number of '1' bits" (also known as Hamming Weight or Population Count / popcount). A loop over every bit position works, but the count only needs one step per set bit: Kernighan's Bit Trick, n & (n - 1). At scale the same count runs word by word over large bitmaps, where each sparse word finishes in a few rounds.

CONSTRAINTS & BOUNDS

LeetCode gives 1≤n≤231−11 \le n \le 2^{31} - 11≤n≤231−1, so n has at most 31 set bits and the loop runs at most 31 times. It stops as soon as n reaches 0.

FAANG PRODUCTION TRAPS & EDGE CASES

If an API can pass a negative value (a signed 32-bit register holding unsigned data), mask it to 32 bits first: while n > 0 returns 0 at once for a negative number, and while n: never ends on a negative Python int. Edge cases: n=1n = 1n=1 (1 round) and n=231−1n = 2^{31} - 1n=231−1 (31 rounds).

© 2026 Hi👋WebEnterprise. All rights reserved.
Sitemap•llms.txt•