Algorithm


Problem Name: 738. Monotone Increasing Digits

An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.

Given an integer n, return the largest number that is less than or equal to n with monotone increasing digits.

 

Example 1:

Input: n = 10
Output: 9

Example 2:

Input: n = 1234
Output: 1234

Example 3:

Input: n = 332
Output: 299

 

Constraints:

  • 0 <= n <= 109

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


function monotoneIncreasingDigits(N) {
  const arr = (''+N).split('').map(el => +el)
  let mark = arr.length
  for(let i = arr.length - 1; i > 0; i--) {
    if (arr[i]  <  arr[i - 1]) {
      mark = i - 1
      arr[i - 1]--
    }
  }
  for(let i = mark + 1; i < arr.length; i++) {
    arr[i] = 9
  }

  return arr.join('')
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 10

Output

x
+
cmd
9

#2 Code Example with Python Programming

Code - Python Programming


class Solution:
    def monotoneIncreasingDigits(self, N):
        """
        :type N: int
        :rtype: int
        """
        n, pos = str(N), 0
        for i, char in enumerate(n):
            if i>0 and int(n[i])<int(n[i-1]): return int("".join(n[:pos])+str(int(n[pos])-1)+"9"*(len(n)-1-pos)) if int(n[pos])>1 else int("9"*(len(n)-1-pos))
            elif i>0 and n[i] != n[i-1]: pos = i
        return N
Copy The Code & Try With Live Editor

Input

x
+
cmd
n = 10

Output

x
+
cmd
9
Advertisements

Demonstration


Previous
#736 Leetcode Parse Lisp Expression Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#739 Leetcode Daily Temperatures Solution in C, C++, Java, JavaScript, Python, C# Leetcode