另一位答主的方法需要用
num = str(num)
的方法先把需要求位和的数字转化成字符串在进行计算,这里介绍一个不需要这样转化的递归写法:
def getSum(num):
if num // 10 == 0:
return num
return num % 10 + getSum(num // 10)
输入输出:
输入:
456
输出
15
输入:
23456
输出:
20
def solution(num):
sum = 0
for i in num:
sum = sum + int(i)
return sum
if __name__ == '__main__':
num = input('input number')
print(solution(num))
num=“xxx”
print(sum([int(x) for x in num]))
n=eval(input())
s=0
while n>0:
s=s+n%10
n=n//10
print(s)
input_number = "12345"sum = 0for digit in input_number:
sum += int(digit)print(sum)