博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Codewars第四天--Sum of Digits / Digital Root
阅读量:4302 次
发布时间:2019-05-27

本文共 902 字,大约阅读时间需要 3 分钟。

Codewars第四天–Sum of Digits / Digital Root

题目描述:

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/

你可能感兴趣的文章
oop_day03_内存管理、引用类型数组
查看>>
Java小游戏之打飞机(二)
查看>>
oop_day04_继承、重写_20150812
查看>>
Java笔试面试题006
查看>>
oop_day05_package、public、static、final、内部类
查看>>
oop_day06_抽象类、接口_20150814
查看>>
Java笔试面试题007
查看>>
Java 抽象类与接口的区别
查看>>
oop_day07_多态_20150815
查看>>
Java笔试面试题008
查看>>
Java之面向对象详细总结
查看>>
Java笔试面试题009
查看>>
Java笔试面试题010
查看>>
【JavaSE】day01_ API文档 、 字符串基本操作
查看>>
写给java程序员的一封情书
查看>>
【JavaSE】day02_正则表达式 、 Object 、 包装类
查看>>
【Java】Java小游戏之Shoot游戏源码及详解
查看>>
【JavaSE】day03_Date、SimpleDateFormat、Calendar、Collection
查看>>
【JavaSE】day04_Collection_Iterator_新循环_泛型
查看>>
【JavaSE】day05_List集合_List排序_队列和栈
查看>>