We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

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

Difficulty: Medium


Problem Description

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.


Key Insights

  • The binary representation can be treated as a sequence of bits to determine the number's parity.
  • Operations depend on whether the number is odd or even:
    • Odd numbers require an addition operation to make them even.
    • Even numbers can be halved, significantly reducing their value.
  • The process continues until the number is reduced to 1.

Space and Time Complexity

Time Complexity: O(n), where n is the number of bits in the binary string. Space Complexity: O(1), as we only use a fixed amount of space for variables.


Solution

To solve this problem, we can track the number of operations needed to reduce the binary number to 1 by simulating the process:

  1. Convert the binary string to an integer.
  2. Use a loop to repeatedly check if the number is odd or even.
  3. If odd, increment the count and add 1 to the number; if even, increment the count and divide the number by 2.
  4. Continue until the number reaches 1.

This approach effectively utilizes basic arithmetic operations and a loop to count the steps.


Code Solutions

def numSteps(s: str) -> int:
    count = 0
    num = int(s, 2)  # Convert binary string to integer
    
    while num > 1:
        if num % 2 == 0:  # Check if even
            num //= 2  # Divide by 2
        else:  # If odd
            num += 1  # Add 1
        count += 1  # Increment the step count
    
    return count
← Back to All Questions