Switch indexes, create the next highest number using the same exact 9 digits presented

后端 未结 3 1707
自闭症患者
自闭症患者 2020-11-28 16:07

So I received a challenge that states the following: \"Design a program that takes as input a 9 digit number where no digit appears twice and produces as output an arrangeme

3条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 16:56

    I am not convinced that your approach of flipping digits is guaranteed to find the next highest number (at least not without further checks)

    Here a simple solution: Simply increment the input number and check if the conditions are met or if no number can be found.

    set() can be used to get the set of unique digits in the number.

    input_num = '781623954'
    next_num = int(input_num) + 1
    input_digits = set(input_num)
    found = False
    while not found:
        next_num += 1
        next_digits = set(str(next_num))
        found = len(next_digits) == 9 and input_digits == next_digits
        if next_num > 987654321:
            break
    
    if found:
        print(next_num)
    else:
        print("No number was found.")
    

提交回复
热议问题