如何将数字的数字相加直到有一个

问题描述 投票:0回答:1

我想解决这个问题,但我不知道如何解决

非常感谢您的帮助

给定n,如果该值有多于一位数字,则取n的数字之和,继续直到只有一位

预期输出:

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

我尝试过这个,但我不知道如何重复它,直到只有一位数字

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)
python function sum digits
1个回答
0
投票

使用递归函数对数字的数字进行求和,直到只剩下一位数字。

def sum_digits(n):

   list_of_digits = list(map(int, str(n)))

   digit_sum = sum(list_of_digits)

   # If the sum has more than one digit, call the function recursively

   if digit_sum >= 10:
     return sum_digits(digit_sum)
   else:
     return digit_sum
© www.soinside.com 2019 - 2024. All rights reserved.