首页 > 解决方案 > 位数递减的最小数

问题描述

我发现了一个实现函数的问题,该函数将正整数 n 作为输入并返回大于 n 且位数在减少的最小正整数,类似地对于返回大于 n 且位数在增加的最小正整数的函数。我认为递增函数工作正常。但是函数减少的错误是什么?对于输入 reduction(100),它返回 11 而不是 110。

# the next integer whose digits are increasing.
def increasing(n):
    asastring = str(n)
    length = len(asastring)
    if asastring == "9"*length:
        return "1"*(length+1)
    if length == 1:
        return int(n)+1

    if length >= 2:
        firstcharacter = asastring[0]
        secondcharacter = asastring[1]
        if int(firstcharacter) > int(secondcharacter):
            return int(str(firstcharacter)*length)
        if firstcharacter == secondcharacter:
             return firstcharacter+str(increasing(int(asastring[1:])))
        if int(firstcharacter) < int(secondcharacter):
            if secondcharacter == "9":
                return str(int(firstcharacter)+1) * len(str(n))
            return firstcharacter+str(increasing(int(asastring[1:])))

# the next integer whose digits are decreasing.
def decreasing(n):
    asastring = str(n)
    length = len(asastring)
# First the case where we need to add a digit.
    if asastring == "9"*length:
        return "1"+"0"*length
# Now we know that the next integer has the same number of digits as the original number.
    if length == 1:
        return int(n)+1
    if length >= 2:
        firstcharacter = asastring[0]
        secondcharacter = asastring[1]
        if int(firstcharacter) > int(secondcharacter):
            endpart = str(((asastring[1:3])))
            value = firstcharacter + str(decreasing(int(asastring[1:])))
            return str(firstcharacter) + str(decreasing(int(asastring[1:])))
        if int(firstcharacter) == int(secondcharacter):
            return decreasing(firstcharacter+str(decreasing(int(asastring[1:]))))
        if int(firstcharacter) < int(secondcharacter):
            return str(int(firstcharacter)+1)+'0'*(length-1)

i=100
print(increasing(i))
print(decreasing(i))

标签: pythonrecursion

解决方案


您需要删除递归调用中完成的 int 类型转换,因为 int('00') 正在将您的数字转换为零(基本上删除所有起始零)并缩短字符串的长度。只需删除该铸造..其余代码工作正常:

def decreasing(n):
    asastring = str(n)
    length = len(asastring)
# First the case where we need to add a digit.
    if asastring == "9"*length:
        return "1"+"0"*length
# Now we know that the next integer has the same number of digits as the original number.
    if length == 1:
        return int(n)+1
    if length >= 2:
        firstcharacter = asastring[0]
        secondcharacter = asastring[1]
        if int(firstcharacter) > int(secondcharacter):
            return str(firstcharacter) + str(decreasing(asastring[1:]))
        if int(firstcharacter) == int(secondcharacter):
            return decreasing(firstcharacter+str(decreasing(asastring[1:])))
        if int(firstcharacter) < int(secondcharacter):
            return str(int(firstcharacter)+1)+'0'*(length-1)

推荐阅读