Leetcode 2710. Remove Trailing Zeros From a String
You are given a string num
representing a large integer. You need to return the string but with all trailing zeros removed.
num
?
"0000"
)?
"0"
in this case.To remove the trailing zeros from the string:
"0"
.Here is the Java code to achieve the solution:
public class Solution {
public String removeTrailingZeros(String num) {
// Get the length of the string
int length = num.length();
// Traverse from the end of the string until first non-zero character is found
int i = length - 1;
while (i >= 0 && num.charAt(i) == '0') {
i--;
}
// If all characters are zeros, return "0"
if (i == -1) {
return "0";
}
// Return substring from 0 to (i + 1)
return num.substring(0, i + 1);
}
public static void main(String[] args) {
Solution sol = new Solution();
// Test cases
System.out.println(sol.removeTrailingZeros("12345000")); // Output: "12345"
System.out.println(sol.removeTrailingZeros("1000")); // Output: "1"
System.out.println(sol.removeTrailingZeros("0000")); // Output: "0"
System.out.println(sol.removeTrailingZeros("370")); // Output: "37"
}
}
The time complexity of this solution is O(n) where n
is the length of the string. This is because in the worst case, we need to check each character of the string once from the end of the string towards the beginning. The substring operation also operates in O(n) in the worst case, but since it’s implemented using a reference to the original array in Java, it is very efficient.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?