zoukankan      html  css  js  c++  java
  • 【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
  • 相关阅读:
    字符串转为日期,日期转为字符串
    myeclipse集成jad反编译步骤
    打开指定大小的新窗口和window.open参数
    oracle查看被锁的表和解锁
    修改weblogic端口的方法
    公司治理法律风险防范
    js 动态控制 input 框 的只读属性
    用JS实现改变文本框的只读属性
    Javascript:window.close()不起作用?
    C++学习笔记之this指针
  • 原文地址:https://www.cnblogs.com/seyjs/p/8001046.html
Copyright © 2011-2022 走看看