mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
添加 0738.单调递增的数字.md Scala版本
This commit is contained in:
@ -246,7 +246,37 @@ function monotoneIncreasingDigits(n: number): number {
|
||||
```
|
||||
|
||||
|
||||
### Scala
|
||||
|
||||
直接转换为了整数数组:
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def monotoneIncreasingDigits(n: Int): Int = {
|
||||
var digits = mutable.ArrayBuffer[Int]()
|
||||
// 提取每位数字
|
||||
var temp = n // 因为 参数n 是不可变量所以需要赋值给一个可变量
|
||||
while (temp != 0) {
|
||||
digits.append(temp % 10)
|
||||
temp = temp / 10
|
||||
}
|
||||
// 贪心
|
||||
var flag = -1
|
||||
for (i <- 0 until (digits.length - 1) if digits(i) < digits(i + 1)) {
|
||||
flag = i
|
||||
digits(i + 1) -= 1
|
||||
}
|
||||
for (i <- 0 to flag) digits(i) = 9
|
||||
|
||||
// 拼接
|
||||
var res = 0
|
||||
for (i <- 0 until digits.length) {
|
||||
res += digits(i) * math.pow(10, i).toInt
|
||||
}
|
||||
res
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
Reference in New Issue
Block a user