当前位置: 首页 > 工具软件 > Monotone > 使用案例 >

[LeetCode]Monotone Increasing Digits@Python

何安宜
2023-12-01

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

Input: N = 332
Output: 299

Solution

class Solution:
    def monotoneIncreasingDigits(self, N: int) -> int:
        if N<10: return N
        temp = list(str(N))
        i, n = 0, len(temp)
        
        while i<n-1 and temp[i]<=temp[i+1]: i+=1
        
        if i==n-1: return N
        
        while i>0 and temp[i]==temp[i-1]: i-=1
        
        temp[i]=str(int(temp[i])-1)
        temp[i+1:]=['9']*(n-i-1)
        
        return int(''.join(temp))
 类似资料: