Python 1342.py
class Solution:
def numberOfSteps(self, num: int) -> int:
result = 0
while num > 0:
result += num & 1
num >>= 1
if num > 0:
result += 1
return result
Difficulty
and has an acceptance rate of about 86% (1+ million submissions).
Typical patterns to solve this problem:
- Bit Manipulation
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method numberOfSteps that computes the number of operations required to reduce a non-negative integer to zero. The reduction follows a rule set where each iteration either removes the least-significant set bit or performs a single right shift, effectively counting the steps needed to clear all bits. The implementation relies exclusively on bitwise operators and a simple loop, delivering a compact and efficient solution.
Key Steps
Initialization
The method begins by establishing a counter named result set to zero. This counter accumulates the total number of steps taken throughout the execution.
result = 0
Loop Condition
A while loop drives the process, continuing as long as the input num remains greater than zero. This condition guarantees that the loop terminates precisely when all bits have been cleared.
while num > 0:
Bitwise Accumulation
Inside the loop, the expression num & 1 extracts the least-significant bit of num. Adding this value to result accounts for a step when the current bit is set (i.e., when the number is odd).
result += num & 1
Shift Operation
The statement num >>= 1 performs a right arithmetic shift, discarding the least-significant bit that has just been examined. This operation effectively divides the number by two without using division, preparing the next iteration to examine the new least-significant bit.
num >>= 1
Conditional Increment
After the shift, the code checks whether any bits remain (num > 0). If so, it adds one more to result. This extra increment represents the step of performing the shift itself, which is counted only when there is still work to do.
if num > 0:
result += 1
Return Value
When the loop exits, result holds the total count of steps required to reduce the original number to zero, and the method returns this value.
return result
Edge Cases Handled
When the input num is zero, the loop condition while num > 0 fails immediately, leaving result at its initial value of zero. This correctly reflects that no steps are needed for an already zero value.
For numbers that are powers of two, the binary representation contains a single set bit followed by zeros. The loop processes the single set bit, adds one for the bit removal, then performs successive right shifts. The conditional increment ensures that each shift is counted until the number becomes zero, accurately capturing the total steps for such inputs.
Odd numbers trigger the result += num & 1 line on every iteration because the least-significant bit is always one. The subsequent shift removes that bit, and the conditional increment adds the cost of the shift, handling the alternating pattern of subtraction and division that characterizes odd inputs.
Even numbers skip the addition from num & 1 because the least-significant bit is zero, but they still incur a step for the shift via the conditional increment, correctly modeling the division-by-two operation without an explicit subtraction step.
Performance Optimizations
The algorithm leverages bitwise operators (& and >>) instead of arithmetic operations such as modulo or division. Bitwise operations execute in constant time on modern processors, providing a speed advantage over higher-level arithmetic.
By combining the detection of a set bit and the shift into a single loop iteration, the code minimizes the number of loop cycles needed to process each bit. The conditional increment after the shift avoids an unnecessary addition when the number has already reached zero, preventing a superfluous step count.
The use of a single integer variable for the accumulator and the in-place modification of num reduces memory overhead and improves cache locality, contributing to overall efficiency. The straightforward control flow eliminates function calls or recursion, ensuring that the execution path remains tight and predictable.
ELI5 - Simplified Explanation
Imagine there is a magical toy box filled with building blocks. The goal is to make the toy box completely empty. To do this, a special robot follows two simple rules. If the number of blocks in the box is an odd number, the robot takes one single block out and sets it aside. If the number of blocks is an even number, the robot takes half of the blocks away at once. Every single time the robot performs one of these actions, a counter tracks it like a scorekeeper marking down each step. The robot keeps looking into the box and repeating these actions until there are no blocks left inside. This code tracks the count of those actions to tell how many steps it takes to reach zero.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | |||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 2139: Minimum Moves to Reach Target Score
- problem 2169: Count Operations to Obtain Zero
Solved On The Same Day
- problem 1184: Distance Between Bus Stops
- problem 1399: Count Largest Group
- problem 1496: Path Crossing
- problem 1646: Get Maximum in Generated Array
- problem 1893: Check if All the Integers in a Range Are Covered
- problem 2404: Most Frequent Even Element
- problem 2432: The Employee That Worked on the Longest Task
- problem 2451: Odd String Difference
- problem 2540: Minimum Common Value
- problem 609: Find Duplicate File in System
- problem 1169: Invalid Transactions
- problem 1711: Count Good Meals
- problem 1781: Sum of Beauty of All Substrings
- problem 1865: Finding Pairs With a Certain Sum
- problem 1871: Jump Game VII
- problem 2013: Detect Squares
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality