Leetcode Problem 1404. Number of Steps to Reduce a Number in Binary Representation to One

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

Leetcode Solutions

Simulate the Process

  1. Initialize carry to 0 and steps to 0.
  2. Iterate through the binary string from the second last character to the first character (right to left), skipping the first character since it's always '1'.
  3. For each character: a. If the character is '0' and there is no carry, increment steps by 1 (even number, divide by 2). b. If the character is '1' and there is a carry, increment steps by 1 (odd number, already added 1 due to carry). c. If the character is '0' but there is a carry, or the character is '1' without a carry, increment steps by 2 (odd number, add 1 and divide by 2).
  4. After the loop, if there is a carry, increment steps by 1 to account for the final addition that results in '10'.
  5. Return the total number of steps.
UML Thumbnail

Convert to Integer and Simulate

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...