Merge pull request #2002 from fwqaaq/patch-32

Update 0738.单调递增的数字.md 优化 rust
This commit is contained in:
程序员Carl
2023-04-17 10:34:34 +08:00
committed by GitHub

View File

@ -280,18 +280,20 @@ object Solution {
```Rust
impl Solution {
pub fn monotone_increasing_digits(n: i32) -> i32 {
let mut str_num = n.to_string().chars().map(|x| x.to_digit(10).unwrap() as i32).collect::<Vec<i32>>();
let mut flag = str_num.len();
for i in (1..str_num.len()).rev() {
if str_num[i - 1] > str_num[i] {
let mut n_bytes = n.to_string().into_bytes();
let mut flag = n_bytes.len();
for i in (1..n_bytes.len()).rev() {
if n_bytes[i - 1] > n_bytes[i] {
flag = i;
str_num[i - 1] -= 1;
n_bytes[i - 1] -= 1;
}
}
for i in flag..str_num.len() {
str_num[i] = 9;
for v in n_bytes.iter_mut().skip(flag) {
*v = 57;
}
str_num.iter().fold(0, |acc, x| acc * 10 + x)
n_bytes
.into_iter()
.fold(0, |acc, x| acc * 10 + x as i32 - 48)
}
}
```