mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 15:09:40 +08:00
738go版本答案更正(原答案力扣无法通过)
This commit is contained in:
@ -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
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
</a>
|
||||
|
||||
|
Reference in New Issue
Block a user