Remove Trailing Zeros From a String

You have a given string representation of a positive integer, and you need to remove all trailing zeros from that number.

Here’s a step-by-step guide to solve this problem:

  1. Start from the End: As we need to remove the trailing zeros, we will start from the end of the string.
  2. Iterate Backwards: Iterate through the string from right to left until you find a character that is not a ‘0’.
  3. Construct the Result: The string without trailing zeros consists of all characters from the beginning of the string to the last non-zero character.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
    def removeTrailingZeros(self, num: str) -> str:
        index = len(num) - 1

        # Iterate from the end of the string to the beginning
        while index >= 0 and num[index] == '0':
            index -= 1

        # Return the string without trailing zeros
        return num[:index + 1]

Explanation

  • The while loop continues as long as we encounter zeros from the end of the string. Once we find a non-zero digit, we know where the trailing zeros end.
  • By slicing the string from the beginning to the index of the last non-zero character, we obtain the result without trailing zeros.

Example

For the input num = "51230100", the loop will iterate from the end until it reaches the digit ‘1’, and then the resulting string will be "512301".

This solution adheres to the constraints and provides an efficient way to remove trailing zeros from the given string representation of a number.