#1342
Number of Steps to Reduce a Number to Zero
EasyMathBit ManipulationBit ManipulationBinary Representation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(log n)Space O(1)
The optimal solution leverages the properties of binary representation. Each time we divide by 2, we are effectively shifting the bits of the number to the right. This means that the number of steps can be calculated based on the number of bits in the binary representation of the number, along with the number of 1s (which represent the odd numbers).
⚙️
Algorithm
3 steps- 1Step 1: Count the number of bits in the binary representation of num.
- 2Step 2: Count the number of 1s in the binary representation of num.
- 3Step 3: The total steps will be the number of bits (which represents the divisions by 2) plus the number of 1s (which represents the subtractions).
solution.py2 lines
1def numberOfSteps(num):
2 return bin(num).count('1') + num.bit_length() - 1ℹ
Complexity note: The time complexity is O(log n) because we are dealing with the number of bits in the binary representation of num. The space complexity is O(1) as we are not using any additional data structures.
- 1Understanding binary representation can simplify problems involving powers of two.
- 2Counting bits can often lead to more efficient solutions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.