Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 8bf4e2c

Browse files
committed
738go版本答案更正(原答案力扣无法通过)
1 parent 1c878ba commit 8bf4e2c

File tree

1 file changed

+15
-16
lines changed

1 file changed

+15
-16
lines changed

problems/0738.单调递增的数字.md

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -273,22 +273,20 @@ class Solution:
273273
### Go
274274
```go
275275
func 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+

0 commit comments

Comments
 (0)