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.
numbers = [1, 2]
def sum_of_digits(n):
for n in
sum_of_digits(343)
The output I'm trying to achieve: 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)
:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.