Statementâ–¼
You are given a string, str
, as a binary representation of an integer. Your task is to return the number of steps needed to reduce it to
If the number is even, divide it by
2 .If the number is odd, add
1 to it.
You can always reach 1 for all provided test cases.
Constraints:
1<= str.length
Â<=500 str
 consists of characters′0′ or′1′ str[0]== ′1′
Solution
The idea of the solution is to use a greedy approach to count the steps needed to reduce a binary number to
Now, let’s walk-through the steps of the solution.
Initialize the variable,
steps
, with0 .Initialize the variable,
c
, to store carryover with0 .Iterate through each digit from the end of the
str
to the second digit:Add the current digit and
c
.If the result is odd:
Increment
steps
by2 .Set
c
to1 .
Otherwise, If the result is even:
Increment
steps
by1 .
Return the sum of
steps
andc
as the total step count.
Let’s look at the following illustration to get a better understanding of the solution: