我是一名CS学生,大约一周前买了《 Cracking the Coding Interview》。我只是在Big O一章中,我发现了一种算法,该算法应该将数字中的数字求和。乍一看它似乎令人困惑,所以我在Python中运行了它,但是它没有完成应有的操作。看看:
int sumDigits(int n) {
int sum= 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
据我了解,这段代码实际上没有返回给定数字的位数总和,还是这样?我真的很想看看它是如何实现的,但是由于我在Python中尝试过的示例不起作用,所以我真的看不到它是如何起作用的。
答案 0 :(得分:4)
此算法取决于n /= 10
是integer division(即5/2 === 2
)。如果您使用的是Python 3,则需要使用//
,因此它应该看起来像这样:
def sumDigits(n):
sum = 0
while n > 0:
sum += n % 10
n //= 10 # integer division
return sum
sumDigits(123) # 6
答案 1 :(得分:1)
The code is correct and would work as intended. You can dry run the code. Take for example the number 1234. Here is the output after each iteration of the while loop.
Sum Number
0 1234
4 123
7 12
9 1
10 0
It is evident that in each iteration of the while loop, the last digit given by n % 10 is added to the sum. Also, the number itself is divided by 10 (n /= 10) in the next step so that the 2nd last digit now becomes the last digit post division and can safely be added to the sum.