Python 数字总和计算器
使用 Python 中的数学运算符计算整数中各个数字的总和。
概述
计算数字之和涉及按顺序提取数字的每个数字并累加值。
在 Python 中,这可以使用两种主要技术来实现:使用模“% 10”和底除“// 10”的算术循环,或字符串转换迭代。
该算术方法在 O(log n) 时间和 O(1) 空间中运行,使其高效且与语言无关。
代码和执行输出
具有绝对值的数字算术和函数支持负数。
sum_of_digits.py
在编辑器中尝试def sum_digits(n):
n = abs(n)
total = 0
while n > 0:
total += n % 10 # Extract last digit
n //= 10 # Remove last digit
return total
print("Sum of digits for 12345:", sum_digits(12345))
print("Sum of digits for 908: ", sum_digits(908))端子输出
Sum of digits for 12345: 15
Sum of digits for 908: 17逐步实施
- 数学中的数字根计算
- 校验和验证和散列算法
- 美学和数字命理学编码难题
常见问题解答
这可以在 Python 中用一行完成吗?
是的!您可以将数字转换为字符串,将每个字符转换回整数,并对它们求和:`sum(int(d) for d in str(abs(n)))`。