2024-04-26 21:32:11 发布
网友
这个问题:
输入:123456
结果:
1+2+3+4+5+6 = 21 2+1 = 3
回报:3
这是我的代码:
num = input() print(sum(list(map(int, list(num)))))
我不知道怎么做,直到它是1位数
试试这个(IPython中的示例):
In [1]: s = '123456' Out[1]: '123456' In [2]: digits = [int(j) for j in s] Out[2]: [1, 2, 3, 4, 5, 6] In [3]: s = str(sum(digits)) Out[3]: '21'
重复步骤2和步骤3,直到len(s) == 1
len(s) == 1
单向:
while len(str(ans))>1: ans = sum(map(int, str(ans)))
完整代码:
num = 45637 ans = num while len(str(ans))>1: ans = sum(map(int, str(ans))) print(ans)
输入45637的输出:
7
您可以尝试以下方法:
s = input() while(len(s)>1): s = str(sum(list(map(int,s))))
试试这个(IPython中的示例):
重复步骤2和步骤3,直到
len(s) == 1
单向:
完整代码:
输入45637的输出:
您可以尝试以下方法:
相关问题 更多 >
编程相关推荐