【leetcode】Monotone Increasing Digits

本文介绍了一种算法,用于寻找小于或等于给定非负整数N的最大整数,该整数具有单调递增的数字特征。通过从最低位开始检查每个数字并相应地调整它们,确保整数满足条件。
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
Note: N is an integer in the range [0, 10^9].

 

解题思路:本题要求的是找出一个前一位不大于后一位的整数,并且这个整数不能大于输入的数。最直接的方法,是从输入数开始判断,依次减一,直到找到符合条件的数为止。更为简便的方法可以这样,从输入数的最低位开始依次和前一位比较,如果前一位大于后一位,那么前一位减1,后面所有位的值都置为9,直到遍历到最高位为止。例如输入数为762543。从最低位3开始找,次低位的是4小于5,把4和3都置为9,5减1变成4。第一次变换后的值为762499,继续找到6小于2,所以变换成759999,最后5小于7,变成699999。

代码如下:

class Solution(object):
    def monotoneIncreasingDigits(self, N):
        """
        :type N: int
        :rtype: int
        """
        sn = str(N)
        sn = sn[::-1]
        l = []
        for i in sn:
            l.append(int(i))
        for i in range(len(l)-1):
            if l[i] >= l[i+1]:
                continue
            else:
                #l[i] = 9
                for j in range(i+1):
                    l[j] = 9
                l[i + 1] -= 1
        res = 0
        count = 0
        for i in l:
            res += i*pow(10,count)
            count += 1

        return res

 

转载于:https://www.cnblogs.com/seyjs/p/8001046.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值