[英]Adding Digits in a Number (Need Code Explanation)
I came across this code segment elsewhere. 我在其他地方遇到过此代码段。 It simply adds all the digits in a given number: 它只是将所有数字加到给定的数字中:
def sumDigits(n):
sum = 0
while n > 0:
sum += n % 10
n //= 10
return sum
Problem is, I don't get the logic behind it at all. 问题是,我根本没有逻辑。 In particular, I don't get exactly what the loop does: 特别是,我不完全了解循环的作用:
while n > 0:
sum += n % 10 # Why n % 10?
n //= 10 # Again, not sure why we divide the number by 10
Could someone provide me with an example of how the algorithm works? 有人可以向我提供该算法如何工作的示例吗?
Thanks! 谢谢!
You should understand 2 things: 您应该了解两件事:
n % 10
give you the rightmost digit of a number. n % 10
为您提供数字的最右边数字。 For example: 123 % 10 = 3
例如: 123 % 10 = 3
n // 10
remove the rightmost digit of a number. n // 10
删除数字的最右边数字。 For example: 123 // 10 = 12
例如: 123 // 10 = 12
so if you repeat that process you get the desired result 因此,如果重复该过程,您将获得所需的结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.