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. If the current number is even, divide it by 2; if it is odd, add 1. Reaching 1 is always possible.

30:00

Number of Steps to Reduce a Number in Binary Representation to One
medium
Free written solution
Topics
Companies

Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1. If the current number is even, divide it by 2; if it is odd, add 1. Reaching 1 is always possible.

Example 1:
Input: {"s":"1101"}
Output: 6
Constraints:
  • 1≤s.length≤5001 \leq s.length \leq 500

  • s consists of '0' and '1' only

  • s[0] == '1'

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"1101"}

Scan s = "1101" from the lowest bit. Each bit costs one ÷2 to shift out, plus one +1 first if the number is odd at that moment.

bits shift out from the right, one ÷2 each

carry 0
steps 0
1

.

1

.

0

.

1

.

+1 ÷2 = odd: 2 steps, carry becomes 1

÷2 = even: 1 step

pink ring = where the carry lands next

Variables
VariableValue
steps0
carry0
DepthFunction Call
Stack empty
0/5