栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Codewars:Sum of Digits / Digital Root

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/423527.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号