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

后端 未结 8 1861
无人及你
无人及你 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:34

    If you like recursion, and you must:

    >>> def sum_digits_rec(integ):
            if integ <= 9:
                return integ
            res = sum(divmod(integ, 10)) 
            return sum_digits(res)
    
    >>> print(sum_digits_rec(98765678912398))
    7
    
    0 讨论(0)
  • 2020-12-21 02:35

    you can try this solution, if n=98 then your output will be 8

    def repitative_sum(n):
        j=2
        while j!=1:
            n=str(n)
            j=len(n)
            n=list(map(int,n))
            n=sum(n)
        print(n)
    
    0 讨论(0)
  • 2020-12-21 02:53
    def digit_sum(num):
        if num < 10:
            return num
        last_digit = num % 10
        num = num / 10
        return digit_sum(last_digit + digit_sum(num))
    
    input_num = int(input("Enter an integer: "))
    print("result : ",digit_sum(input_num))
    

    This may help you..!

    0 讨论(0)
  • This should work, no division involved.

    n = int(input("Input an integer:"))
    while n > 9:
        n = sum(map(int, str(n)))
    print(n)
    

    It basically converts the integer to a string, then sums over the digits using a list comprehension and continues until the number is no greater than 9.

    0 讨论(0)
  • 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))
    
    0 讨论(0)
  • 2020-12-21 02:56

    I'm not sure if it's anti-practice in Python because I know nothing about the language, but here is my solution.

    n = int(input("Input an integer:"))
    
    def sum_int(num):
        numArr = map(int,str(num))
        number = sum(numArr)
        if number < 10:
            print(number)
        else:
            sum_int(number)
    
    sum_int(n)
    

    Again I am unsure about the recursion within a function in Python, but hey, it works :)

    0 讨论(0)
提交回复
热议问题