Skip to content Skip to sidebar Skip to footer

How To Make Loop Repeat Until The Sum Is A Single Digit?

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 number 2345

Solution 1:

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.

Solution 2:

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

defrepitative_sum(n):
    j=2while j!=1:
        n=str(n)
        j=len(n)
        n=list(map(int,n))
        n=sum(n)
    print(n)

Solution 3:

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

defsum_digits(n):
    newnum = 0while 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)

Solution 4:

You could utilize recursion.

Try this:

defsum_of_digits(n):
    s = 0while n:
        s += n % 10
        n //= 10if s > 9:
        return sum_of_digits(s)

    return s

n = int(input("Enter an integer: "))
print(sum_of_digits(n))

Solution 5:

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:"))

defsum_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 :)

Post a Comment for "How To Make Loop Repeat Until The Sum Is A Single Digit?"