LeetCode 2710. Remove Trailing Zeros From a String
您是打尖儿还是住店呢
编辑于 2023年05月28日 23:06
收录于文集
共500篇

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

 

Example 1:

Input: num = "51230100&#​34;Output: "512301&#​34;Explanation: Integer "51230100&#​34; has 2 trailing zeros, we remove them and return integer "512301&#​34;.

Example 2:

Input: num = "123&#​34;Output: "123&#​34;Explanation: Integer "123&#​34; has no trailing zeros, we return integer "123&#​34;.

 

Constraints:

  • 1 <= num.length <= 1000

  • num consists of only digits.

  • num doesn't have any leading zeros.

使用stringbuilder的方法,因为stringbuilder有reverse的函数。

代码块
JavaScript
自动换行
复制代码
class Solution {
    public String removeTrailingZeros(String num) {
         StringBuilder sb=new StringBuilder();
        int n=num.length();
        int cnt=0;
        for (int i = n-1; i >=0; i--) {
            if(num.charAt(i)=='0'&cnt==0){
                continue;
            }else if(num.charAt(i)=='0'&cnt>0){
                cnt++;
                sb.append(num.charAt(i));
            }else if(num.charAt(i)!='0'){
                sb.append(num.charAt(i));
                cnt++;
            }else if(cnt==0&num.charAt(i)!='0'){
                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.