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 Reduction to One INPUT Binary String s: 1 1 0 1 pos 0 pos 1 pos 2 pos 3 Decimal Value: 13 8 + 4 + 0 + 1 = 13 Rules: If EVEN: divide by 2 If ODD: add 1 Goal: reach 1 ALGORITHM STEPS 1 Scan from right Process bits end to start 2 Count 0s as steps Each 0 = 1 divide op 3 Count 1s as +2 steps Add 1 + divide = 2 ops 4 Handle carry Track when adding 1 Execution Trace: 13 (odd) --> +1 --> 14 14 (even) --> /2 --> 7 7 (odd) --> +1 --> 8 8 (even) --> /2 --> 4 4 (even) --> /2 --> 2 2 (even) --> /2 --> 1 FINAL RESULT Total Steps: 6 Step Breakdown: Add operations: 2 Divide operations: 4 Total: 2 + 4 = 6 Output: 6 [OK] Verified Key Insight: For binary counting: each '0' bit requires 1 operation (divide). Each '1' bit (except leading) requires 2 operations (add 1 to make even, then divide). Use carry flag to track overflow. TutorialsPoint - Number of Steps to Reduce a Number in Binary Representation to One | Optimized Counting
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