File tree Expand file tree Collapse file tree 1 file changed +15
-16
lines changed Expand file tree Collapse file tree 1 file changed +15
-16
lines changed Original file line number Diff line number Diff line change @@ -273,22 +273,20 @@ class Solution:
273273### Go
274274``` go
275275func monotoneIncreasingDigits (n int ) int {
276- s := strconv.Itoa (N)// 将数字转为字符串,方便使用下标
277- ss := []byte (s)// 将字符串转为byte数组,方便更改。
278- n := len (ss)
279- if n <= 1 {
280- return n
281- }
282- for i := n-1 ; i > 0 ; i-- {
283- if ss[i-1 ] > ss[i] { // 前一个大于后一位,前一位减1,后面的全部置为9
284- ss[i-1 ] -= 1
285- for j := i; j < n; j++ { // 后面的全部置为9
286- ss[j] = ' 9'
287- }
288- }
289- }
290- res , _ := strconv.Atoi (string (ss))
291- return res
276+ s := strconv.Itoa (n)
277+ // 从左到右遍历字符串,找到第一个不满足单调递增的位置
278+ for i := len (s) - 2 ; i >= 0 ; i-- {
279+ if s[i] > s[i+1 ] {
280+ // 将该位置的数字减1
281+ s = s[:i] + string (s[i]-1 ) + s[i+1 :]
282+ // 将该位置之后的所有数字置为9
283+ for j := i + 1 ; j < len (s); j++ {
284+ s = s[:j] + " 9" + s[j+1 :]
285+ }
286+ }
287+ }
288+ result , _ := strconv.Atoi (s)
289+ return result
292290}
293291```
294292
@@ -447,3 +445,4 @@ public class Solution
447445<a href =" https://programmercarl.com/other/kstar.html " target =" _blank " >
448446 <img src =" ../pics/网站星球宣传海报.jpg " width =" 1000 " />
449447</a >
448+
You can’t perform that action at this time.
0 commit comments