How to make loop repeat until the sum is a single digit?

后端 未结 8 1862
无人及你
无人及你 2020-12-21 02:26

Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the numb

相关标签:
8条回答
  • 2020-12-21 02:56
    def add_digits(num):
            return (num - 1) % 9 + 1 if num > 0 else 0
    

    A simple, elegant solution.

    0 讨论(0)
  • 2020-12-21 02:57

    You don't need to convert your integer to a float here; just use the divmod() function in a loop:

    def sum_digits(n):
        newnum = 0
        while n:
            n, digit = divmod(n, 10)
            newnum += digit
        return newnum
    

    By making it a function you can more easily use it to repeatedly apply this to a number until it is smaller than 10:

    n = int(input("Input an integer:"))
    while n > 9:
        n = sum_digits(n)
    
    print(n)
    
    0 讨论(0)
提交回复
热议问题