RECURSIVE函数将总和输入的数字 [英] RECURSIVE function that will sum digits of input
本文介绍了RECURSIVE函数将总和输入的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
只是想知道我该如何解决这个问题,并且可能使其递归。这是我到目前为止
def sum_digits3(n):
r = 0
while n:
r,n = r + n%10,n // 10
return r
>>> def foo(n):
n = str(n)
if len(n)== 1:
return int(n)
return foo(sum(int(c) for c in n))
>>> foo(1969)
7
>>>
def foo(n):
n = str(n)
如果len(n)== 1:
返回int(n)
返回foo(sum(int(c)for c in n))
Trying to write a piece of code that will sum the digits of a number. Also I should add that I want the program to keep summing the digits until the sum is only 1 digit.
For example, if you start with 1969, it should first add 1+9+6+9 to get 25. Since the value 25 has more than a single digit, it should repeat the operation to obtain 7 as a final answer.
Was just wondering how I could pull this off and possibly make it recursive as well. This is what I have so far
def sum_digits3(n):
r = 0
while n:
r, n = r + n % 10, n // 10
return r
解决方案
Convert back and forth between strings and ints, make use of sum().
>>> def foo(n):
n = str(n)
if len(n) == 1:
return int(n)
return foo(sum(int(c) for c in n))
>>> foo(1969)
7
>>>
def foo(n):
n = str(n)
if len(n) == 1:
return int(n)
return foo(sum(int(c) for c in n))
这篇关于RECURSIVE函数将总和输入的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文