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

后端 未结 8 1884
无人及你
无人及你 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条回答
  •  旧时难觅i
    2020-12-21 02:56

    You could utilize recursion.

    Try this:

    def sum_of_digits(n):
        s = 0
    
        while n:
            s += n % 10
            n //= 10
    
        if s > 9:
            return sum_of_digits(s)
    
        return s
    
    n = int(input("Enter an integer: "))
    print(sum_of_digits(n))
    

提交回复
热议问题