【发布时间】:2021-01-11 23:45:33
【问题描述】:
我尝试解决 codewars Sum of Digits/Digital Root 问题,您必须:
给定n,取n的数字之和。如果该值超过一位,则继续以这种方式减少,直到产生一位数。输入将是一个非负整数。
所以通过 52 将返回 7,因为 5 + 2 是 7,通过 942 将返回 6,因为 9 + 4 + 2 = 15 然后 1 + 5 = 6。
我想出了这个代码:
def digital_root(n):
n_str = str(n)
digit_total = 0
while len(n_str) != 1:
for digit in n_str:
digit_total += int(digit)
n_str = str(digit_total)
return(n_str)
但它只适用于 2 位数字,它不适用于更高位的数字,它只是无休止地运行。这段代码可能是一种不好的方法,我查看了其他人的答案,我得到了他们的解决方案,但我只是不明白为什么这不适用于更高的数字。
【问题讨论】:
-
是否需要在循环顶部将
digital_total重置为0? -
@xdhmoore 也是这么想的,他需要在分配
n_str后重置digit_total否则他只是再次将之前的结果加到总和中
标签: python