Solution: Number of Steps to Reduce a Binary Number to One

Let’s solve the Number of Steps to Reduce a Binary Number to One problem using the Greedy Techniques pattern.

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 11 by following these rules:

  • If the number is even, divide it by 22.

  • If the number is odd, add 11 to it.

You can always reach 1 for all provided test cases.

Constraints:

  • 1<=1 <= str.length <=500<= 500

  • str consists of characters 0'0' or 1'1'

  • str[0]==str[0] == 1'1'

Solution

The idea of the solution is to use a greedy approach to count the steps needed to reduce a binary number to 11 because, at each stage of the decision-making process, it takes the most immediate and optimal step—if the digit is odd, increment and divide; if the digit is even, divide to minimize the number of operations needed to reduce it to 11. We start from the least significant digit(the rightmost one), and we determine if each digit (after accounting for any previous carry) is even or odd. For an odd digit, we add two steps (one to make it even and one to divide by 22), and for an even digit, we add one step (to divide by 22). This process continues until we reach the most significant digit(the leftmost one). Any carry-over from adding 1 is counted in the final step count. This ensures the total steps needed to reduce the binary number.

Now, let’s walk-through the steps of the solution.

  • Initialize the variable, steps, with 00.

  • Initialize the variable, c, to store carryover with 00.

  • 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 by 22.

      • Set c to 11.

    • Otherwise, If the result is even:

      • Increment steps by 11.

  • Return the sum of steps and c as the total step count.

Let’s look at the following illustration to get a better understanding of the solution:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.