下一个最大数字,相同的数字

时间:2016-11-02 15:58:36

标签: python integer control-flow

我的代码似乎是正确的,但如果不能生成更大的数字,我需要它返回-1:

def next_bigger(n):
    strNum = str(n)
    length = len(strNum)
    for i in range(length-2, -1, -1):
        current = strNum[i]
        right = strNum[i+1]
        if current < right:
            temp = sorted(strNum[i:])
            next = temp[temp.index(current) + 1]
            temp.remove(next)
            temp = ''.join(temp)    
            return int(strNum[:i] + next + temp)
        else: 
            return -1
    return n

我尝试解决此问题的方法无效:添加else是我认为可以替代current大于right的替代方法。

请帮忙!

3 个答案:

答案 0 :(得分:2)

无论如何,你的代码流是错误的:在你的循环中,你有以下结构:

for A :
    if B :
        return
    else :
        return

因此,您的程序将始终在第二次迭代之前终止。

答案 1 :(得分:0)

在某些情况下,修复代码要比重写代码困难得多。我不确定这对你有多大帮助,但请尝试以下代码。

def next_bigger(n):
    str_num = str(n)
    size = len(str_num)
    for i in range(2, size + 1):
        sublist = list(str_num[-i:size])
        temp = sorted(sublist, reverse=True)
        if sublist != temp:
            return int(str_num[:size-i] + ''.join(temp))
    return -1

它的作用是从背面切割数字(从2个元素切片开始并一直到len)并检查是否生成的切片在加入时产生最大数量。如果不是它被下一个更大的替换并返回它。如果这对您有用,请告诉我。

  

实施例

n = 4181536841

sublist = ['4', '1']
temp = ['4', '1']  # they are the same so no larger number can be produced just by looking at a slice of length 2.

#---------iteration 2---------------
sublist = ['8', '4', '1']
temp = ['8', '4', '1']  # they are again the same so no larger number can be produced just by looking at a slice of length 3.

#---------iteration 3---------------
sublist = ['6', '8', '4', '1']
temp = ['8', '6', '4', '1']  # now they are different. So produce a number out of temp (8641) ans stich it to the rest of the number (418153)
return 4181538641

答案 2 :(得分:0)

Ev。 Kounis是错的。例如在4181536841之后的第二大是4181538146,而不是4181538641。

逻辑工作如下:

1 - Find where list[-n] > list[-n - 1]
2 - find next number higher than list[-n] after list[-n]
3 - Switch next highest and list[-n - 1]
4 - reorder the remaining numbers after list[-n] from low to high

e.g. 29357632:
1 - list[-n] = 7 --> 2935[7]632
    since 7 > 5

2 - next highest number after list[-n] (7) is the 6 --> 29357[6]32

3 - switch list[-n-1] and next highest number (switch 5 and 6) --> 
293[6]7[5]32

4 - reorder rest of digits after list[-n-1] (6) --> 2936[7532] > 29362357

所以29357632之后的下一个最高数字是29362357

相关问题