From 8bf4e2cdf1f69ab9a8f733e0c5693236335cff5c Mon Sep 17 00:00:00 2001 From: 1ltwo Date: Mon, 27 Jan 2025 16:08:27 +0800 Subject: [PATCH] =?UTF-8?q?738go=E7=89=88=E6=9C=AC=E7=AD=94=E6=A1=88?= =?UTF-8?q?=E6=9B=B4=E6=AD=A3=EF=BC=88=E5=8E=9F=E7=AD=94=E6=A1=88=E5=8A=9B?= =?UTF-8?q?=E6=89=A3=E6=97=A0=E6=B3=95=E9=80=9A=E8=BF=87=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0738.单调递增的数字.md | 31 +++++++++++++------------- 1 file changed, 15 insertions(+), 16 deletions(-) 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 +