diff --git a/problems/0738.单调递增的数字.md b/problems/0738.单调递增的数字.md index ff438e98..f2cfee04 100644 --- a/problems/0738.单调递增的数字.md +++ b/problems/0738.单调递增的数字.md @@ -273,22 +273,20 @@ class Solution: ### Go ```go func monotoneIncreasingDigits(n int) int { - s := strconv.Itoa(N)//将数字转为字符串,方便使用下标 - ss := []byte(s)//将字符串转为byte数组,方便更改。 - n := len(ss) - if n <= 1 { - return n - } - for i := n-1; i > 0; i-- { - if ss[i-1] > ss[i] { //前一个大于后一位,前一位减1,后面的全部置为9 - ss[i-1] -= 1 - for j := i; j < n; j++ { //后面的全部置为9 - ss[j] = '9' - } - } - } - res, _ := strconv.Atoi(string(ss)) - return res + s := strconv.Itoa(n) + // 从左到右遍历字符串,找到第一个不满足单调递增的位置 + for i := len(s) - 2; i >= 0; i-- { + if s[i] > s[i+1] { + // 将该位置的数字减1 + s = s[:i] + string(s[i]-1) + s[i+1:] + // 将该位置之后的所有数字置为9 + for j := i + 1; j < len(s); j++ { + s = s[:j] + "9" + s[j+1:] + } + } + } + result, _ := strconv.Atoi(s) + return result } ``` @@ -447,3 +445,4 @@ public class Solution +