Skip to content

Latest commit

 

History

History
54 lines (39 loc) · 1.68 KB

738.单调递增的数字.md

File metadata and controls

54 lines (39 loc) · 1.68 KB

https://leetcode-cn.com/problems/monotone-increasing-digits/solution/738dan-diao-di-zeng-de-shu-zi-tan-xin-de-79hn/

难度:中等

题目:

给定一个非负整数 N,找出小于或等于 N 的最大的整数, 同时这个整数需要满足其各个位数上的数字是单调递增。

(当且仅当每个相邻位数上的数字 x 和 y 满足 x <= y 时,我们称这个整数是单调递增的。)

示例:

示例 1:
输入: N = 10
输出: 9

示例 2:
输入: N = 1234
输出: 1234

示例 3:
输入: N = 332
输出: 299

分析

根据示例想想就能了解到,我们从后往前去遍历,若当前数字小于前一位数字时, 我们将当前数字和其后的所有数字都转换为9,这样的操作就能满足最大值。

解题:

class Solution:
    def monotoneIncreasingDigits(self, n):
        s = list(str(n))
        ln = len(s)
        for i in range(ln - 1, 0, -1):
            if s[i] < s[i - 1]:
                s[i - 1] = str(int(s[i - 1]) - 1)
                s[i:] = ['9'] * (ln - i)
        return int(''.join(s))

欢迎关注我的公众号: 清风Python,带你每日学习Python算法刷题的同时,了解更多python小知识。

有喜欢力扣刷题的小伙伴可以加我微信(King_Uranus)互相鼓励,共同进步,一起玩转超级码力!

我的个人博客:https://qingfengpython.cn

力扣解题合集:https://github.com/BreezePython/AlgorithmMarkdown