本文共 902 字,大约阅读时间需要 3 分钟。
题目描述:
In this kata, you must create a digital root function. A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers. Here's how it works (Ruby example given):
digital_root(16)=> 1 + 6=> 7digital_root(942)=> 9 + 4 + 2=> 15 ...=> 1 + 5=> 6digital_root(132189)=> 1 + 3 + 2 + 1 + 8 + 9=> 24 ...=> 2 + 4=> 6digital_root(493193)=> 4 + 9 + 3 + 1 + 9 + 3=> 29 ...=> 2 + 9=> 11 ...=> 1 + 1=> 2
答案为:
def digital_root(n): while n >= 10: n=sum(map(int,str(n))) digital_root(n) return n
使用map()
函数会根据提供的函数对指定序列做映射。第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
int
转换为str
,然后直接使用sum()
对字符串求和。在这里使用一个递归,计算一个新的值会判断其是否是两位数。 转载地址:http://qmmws.baihongyu.com/