Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum digits of a number untill there is one

I want to solve this but I have no idea how to

I´d appreciate your help

given n take the sum of the digits of n if that value has more than one digit continue until there´s only one

Expected output:

16 -> 1 + 6 = 7
942 -> 9 + 4 + 2 = 15 -> 1 + 5 = 6

I tried this but I don´t know how to repeat it untill there is only one digit

Def sum_digit(n):
 list_of_digits = list(map(int,str(n)))

su = []
for x in list_of_digits:
x = sum(list_of_digits)
su = x

print(su)

sum_digit(6784)
like image 550
Ariky Hito Avatar asked Sep 05 '25 00:09

Ariky Hito


1 Answers

You can use a while loop to repeat until the number reduce to a single digit.

def sum_digit(n):
    while n > 9:
        n = sum(int(i) for i in str(n))
    return n

sum_digit(16)
#7

sum_digit(942)
#6
like image 171
Talha Tayyab Avatar answered Sep 07 '25 16:09

Talha Tayyab