【leetcode】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 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