LC 2710.Remove Trailing Zeros From a String

题目描述

这是 LeetCode 上的 2710. 移除字符串中的尾随零 ,难度为简单

给你一个用字符串表示的正整数 num ,请你以字符串形式返回不含尾随零的整数 num

示例 1:

1
2
3
输入:num = "51230100"
输出:"512301"
解释:整数 "51230100" 有 2 个尾随零,移除并返回整数 "512301" 。

示例 2:

1
2
3
输入:num = "123"
输出:"123"
解释:整数 "123" 不含尾随零,返回整数 "123" 。

提示:

  • 1 <= num.length <= 1000
  • num 仅由数字 09 组成
  • num 不含前导零

解答

方法一:模拟

按照要求找到不是尾随零的位置,返回子串即可。

1
2
3
4
5
6
7
8
9
class Solution {
public String removeTrailingZeros(String num) {
int pos = num.length() - 1;
while (num.charAt(pos) == '0') {
--pos;
}
return num.substring(0, pos + 1);
}
}
  • 时间复杂度\(O(N)\),其中 N 为字符串的长度。

  • 空间复杂度\(O(1)\)

每题一图


LC 2710.Remove Trailing Zeros From a String
https://chen-huaneng.github.io/2023/12/13/2023-12-13-2023-12-13-lc-2710/
作者
Abel
发布于
2023年12月13日
更新于
2023年12月13日
许可协议