Codewars:Sum of Digits / Digital Root

Codewars从零开始的python刷题路

Sum of Digits / Digital Root

题目描述:

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 more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.

翻译:

数字根是数字中所有数字的递归和

给定n,取n中每位数字的和,如果它的数字多于一个,重复执行命令直到和为单个数字。输入为非负数字

解题代码

def digital_root(n):
    # ...
    lis = [int(i) for i in str(n)]# 得到每个数字的列表
    n = sum(lis)# 求和
    if n < 10:
        return n
    else:
        return digital_root(n)#如果大于等于10,重复处理

第一眼看到这个题就感觉非常适合用递归来做,但是或许没有必要搞得这么复杂。

其他解法:

def digital_root(n):
    # ...
    while n>9:
        n=sum(map(int,str(n)))
    return n

版权声明:本文为KwK36原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。