简体   繁体   English

python中的递归函数来查找数字的位数之和

[英]Recursive function in python to find the sum of digits of number

I want to use a recursive algorithm for the function, which should print out the sum of all the digits of a given number.我想对函数使用递归算法,它应该打印出给定数字的所有数字的总和。

Here is my code.这是我的代码。 For example, sum_of_digits(343) will return an output of 10.例如, sum_of_digits(343) 将返回 10 的输出。

numbers = [1, 2]
def sum_of_digits(n):
    for n in

sum_of_digits(343)    

The output I'm trying to achieve: 10我试图实现的输出:10

If you have to use recursion, one method would be to get the individual digits by modding n with 10 and adding that to the sum of the remaining digits (computed by sum_of_digits(n // 10) :如果您必须使用递归,一种方法是通过用10 n进行修改并将其添加到剩余数字的总和(由sum_of_digits(n // 10)计算)来获取单个数字:

def sum_of_digits(n):
    if n < 10:
        return n
    return (n % 10) + sum_of_digits(n // 10)

print(sum_of_digits(343))

Output:输出:

10
def sum_of_digits(n):
    result = 0
    for x in str(n):
        result += int(x)
    return result

sum_of_digits(343) # 10

How about this simplest solution:这个最简单的解决方案怎么样:

number = 343

sum_of_digits = sum(map(int, str(number)))
print(sum_of_digits)
10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM