We’re preparing your current view and syncing the latest data.
Number of Steps to Reduce a Number to One (Binary)
gfgYou are given a binary string s representing a number. You need to reduce the number to 1 by repeatedly performing the following operations: If the current number is even, divide it by 2. If the current number is odd, add 1 to it. Return the number of steps to reduce the binary number to 1.
A single line containing the binary string s.
An integer representing the number of steps to reduce s to 1.
1 <= s.length <= 500; s consists only of '0' and '1'; s does not contain leading zeros except for '0' itself.
Example 1
Input
1101
Output
6
Explanation
The binary number 1101 (decimal 13) reduces as follows: 1101 (odd) -> add 1 -> 1110; 1110 (even) -> divide by 2 -> 111; 111 (odd) -> add 1 -> 1000; 1000 (even) -> divide by 2 -> 100; 100 (even) -> divide by 2 -> 10; 10 (even) -> divide by 2 -> 1. Total steps = 6.