Skip to content
Discussion options

You must be logged in to vote

We are given a binary string s that represents a number. The goal is to reduce this number to 1 by performing the following operations:

  • If the number is even, divide it by 2.
  • If the number is odd, add 1 to it.

We need to determine how many steps it takes to achieve this.

Observations

  1. A binary number is even if its last digit is 0 and odd if its last digit is 1.
  2. Dividing a binary number by 2 is equivalent to removing its last digit (s = substr($s, 0, -1)).
  3. Adding 1 to a binary number can sometimes cause a carry that affects the preceding digits.

Approach

Simulate the process step by step:

  1. Start from the least significant bit (rightmost character of the string).
  2. Check if the number is …

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@basharul-siddike
Comment options

@mah-shamim
Comment options

mah-shamim Jan 18, 2025
Maintainer Author

Answer selected by basharul-siddike
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants