Leetcode - Remove K Digits
Leetcode - Smallest Range II

Leetcode - Monotone Increasing Digits

violet posted @ May 14, 2020 04:38:50 AM in 算法 with tags Algorithm Golang Greedy , 281 阅读

https://leetcode.com/problems/monotone-increasing-digits/

Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits.

(Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.)

 

Example 1:

Input: N = 10
Output: 9

Example 2:

Input: N = 1234
Output: 1234

Example 3:

Input: N = 332
Output: 299

 

func monotoneIncreasingDigits(N int) int {
    num := []byte(strconv.Itoa(N))
    flag := len(num)
    for i := len(num)-1; i > 0; i-- {
        if num[i-1] > num[i] {
            flag = i
            num[i-1] -= 1
        }
    }
    for i := flag; i < len(num); i++ {
        num[i] = '9'
    }
    result := 0
    j := 1
    for i := len(num)-1; i >= 0; i-- {
        result += int(num[i] - '0') * j
        j *= 10
    }
    return result
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter