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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值