Given a positive integer represented as a string, return the integer without trailing zeros as a string.
Example 1:
Input: num = "51230100"Output: "512301"Explanation: Integer "51230100" has 2 trailing zeros, we remove them and return integer "512301".
Example 2:
Input: num = "123"Output: "123"Explanation: Integer "123" has no trailing zeros, we return integer "123".
Constraints:
1 <= num.length <= 1000
num consists of only digits.
num doesn't have any leading zeros.
使用stringbuilder的方法,因为stringbuilder有reverse的函数。
class Solution {
public String removeTrailingZeros(String num) {
StringBuilder sb=new StringBuilder();
int n=num.length();
int cnt=0;
for (int i = n-1; i &gt;=0; i--) {
if(num.charAt(i)==&#39;0&#39;&amp;cnt==0){
continue;
}else if(num.charAt(i)==&#39;0&#39;&amp;cnt&gt;0){
cnt++;
sb.append(num.charAt(i));
}else if(num.charAt(i)!=&#39;0&#39;){
sb.append(num.charAt(i));
cnt++;
}else if(cnt==0&amp;num.charAt(i)!=&#39;0&#39;){
cnt++;
sb.append(num.charAt(i));
}
}
return String.valueOf(sb.reverse());
}
} Runtime: 5 ms, faster than 50.00% of Java online submissions for Remove Trailing Zeros From a String.
Memory Usage: 44.4 MB, less than 12.50% of Java online submissions for Remove Trailing Zeros From a String.