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:
- Start from the End: As we need to remove the trailing zeros, we will start from the end of the string.
- Iterate Backwards: Iterate through the string from right to left until you find a character that is not a ‘0’.
- 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
|
|
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.