编写一个函数,该函数需要一个正的int值n并返回最长的数字递增运算-溢出错误

时间:2019-07-31 11:07:46

标签: python-3.x

写一个函数longestIncreasingRun,它接受一个正的int值n并返回最长的递增数字位数。例如

longestIncreasingRun(1232)将返回123,而longestIncreasingRun(27648923679)将返回23679。如果行程长度有平局,则应返回两个行程中较大的一个。因此longestIncreasingRun(123345)将返回345。

运行程序时出现溢出错误,我想知道如何让程序给出正确的输出

def longestDigitRunSequence(n):
    if n<0:
        n-=n
    count=1
    prev=n%10
    num=n%10
    n=n/10
    max=0
    while n:
        digit=n%10
        if digit>=prev:
            if count>max:
                longest=num
                max=count
            elif count==max:
                if num>longest:
                    longest=num
            count=1
            prev=digit
            num=digit
        else:
            num=digit*10**count+num
            prev=digit
            count+=1
        n=n/10
    if count>max:
        longest=num
        max=count
    elif count==max:
        if num>longest:
            longest=num
    return longest
def test():
    print("Testing longestDigitRunSequence()",end="")
    assert(longestDigitRunSequence(1232) == 123)
    assert(longestDigitRunSequence(27648923679) == 23679)
    assert(longestDigitRunSequence(123345) == 345)
    print("Passed")
test()

0 个答案:

没有答案