Number of Steps to Reduce a Number in Binary Representation to One - Problem

Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules:

If the current number is even: divide it by 2.

If the current number is odd: add 1 to it.

It is guaranteed that you can always reach one for all test cases.

Input & Output

Example 1 — Basic Case
$ Input: s = "1101"
Output: 6
💡 Note: "1101" (13) → "1110" (14) → "111" (7) → "1000" (8) → "100" (4) → "10" (2) → "1" (1). Total: 6 steps.
Example 2 — Even Number
$ Input: s = "10"
Output: 1
💡 Note: "10" (2) → "1" (1). Only one division by 2 needed.
Example 3 — Already One
$ Input: s = "1"
Output: 0
💡 Note: Already at 1, no steps needed.

Constraints

  • 1 ≤ s.length ≤ 500
  • s consists only of '0' or '1'
  • s[0] == '1'

Visualization

Tap to expand
Binary Number Step Reduction ProcessInput:"1101"Apply Rules:Odd: +1Even: ÷2Output:6Step Sequence:1101 → 1110 → 111 → 1000 → 100 → 10 → 1Steps: +1, ÷2, +1, ÷2, ÷2, ÷2 = 6 total
Understanding the Visualization
1
Input
Binary string representation
2
Process
Apply reduction rules until reaching '1'
3
Output
Total number of steps taken
Key Takeaway
🎯 Key Insight: Count steps efficiently by analyzing binary patterns - each '1' (except first) adds an extra step beyond base divisions
Asked in
Meta 15 Amazon 12
32.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen