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

Remove Trailing Zeros From a String

Number: 2819

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given a positive integer num represented as a string, return the integer num without any trailing zeros, also as a string.


Key Insights

  • The problem is essentially about string manipulation rather than arithmetic.
  • Trailing zeros only occur at the end of the string.
  • We can use built-in string methods to remove these zeros efficiently.
  • No need for complex data structures; simple string operations suffice.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the num string. Space Complexity: O(n) in the worst case due to the creation of a new string without trailing zeros.


Solution

The solution takes advantage of string manipulation. In many languages, there exists a method to trim characters from a string. The approach is to remove the character '0' starting from the end of the string until a non-'0' character is encountered.

In our implementations:

  • Python uses the rstrip method which efficiently handles trailing character removal.
  • JavaScript uses a reverse loop or regex to achieve the same.
  • C++ and Java manually iterate from the end of the string to find the position of the last non-zero character.

This method directly tackles the problem by focusing on the necessary part of the string, avoiding any unnecessary computation or conversion.


Code Solutions

# Python solution to remove trailing zeros from a string
def removeTrailingZeros(num: str) -> str:
    # Use rstrip() method to remove any trailing '0' characters from the string
    return num.rstrip('0')

# Example usage:
if __name__ == "__main__":
    test_num = "51230100"
    print(removeTrailingZeros(test_num))  # Output: "512301"
← Back to All Questions