Leetcode - Monotone Increasing Digits
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 }