#1404
Number of Steps to Reduce a Number in Binary Representation to One
MediumStringBit ManipulationSimulationBit ManipulationSimulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the properties of binary numbers. Instead of converting to decimal and simulating the steps, we can directly manipulate the binary string to count the steps more efficiently.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a counter for steps.
- 2Step 2: Iterate over the binary string from the end to the beginning.
- 3Step 3: For each character, if it's '0', increment the step counter (divide by 2).
- 4Step 4: If it's '1', increment the step counter (add 1) and then add 1 more step for the subsequent division.
- 5Step 5: Return the total steps.
solution.py10 lines
1# Full working Python code
2
3def num_steps(s):
4 steps = 0
5 for i in range(len(s) - 1, 0, -1):
6 if s[i] == '0':
7 steps += 1 # divide by 2
8 else:
9 steps += 2 # add 1 and then divide by 2
10 return stepsℹ
Complexity note: The time complexity is O(n) because we iterate through the binary string once, and the space complexity is O(1) since we only use a few variables.
- 1Understanding binary representation helps in optimizing the solution.
- 2Simulating the process directly on the binary string can save time and space.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.