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

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, you have to divide it by 2.
  • If the current number is odd, you have to add 1 to it.

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

Example 1
Inputs = "1101"
Output6
"1101" corresponds to 13; applying the odd/even rules takes 6 steps to reach 1.
Example 2
Inputs = "10"
Output1
"10" corresponds to 2, which is even, so dividing by 2 reaches 1 in one step.

Constraints

  • 1 <= s.length <= 500
  • s consists of characters '0' or '1'
  • s[0] == '1'

Asked at 7 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate