2

I'm a CS student and I bought Cracking the Coding Interview about a week ago. I'm just at the Big O chapter and I found an algorithm which supposedly sums the digits in a number; it looked confusing at a first glance so I ran it in Python but it did not do what it was supposed to. Have a look:

int sumDigits(int n) {
  int sum= 0;
  while (n > 0) {
    sum += n % 10;
    n /= 10;
  }
  return sum;
}

From what I understand, this code does not actually return the sum of the digits of a given number, or does it? I really want to see how it does this but since the example I tried in Python did not work I really can't see how this works.

Daniel Hernandez
  • 164
  • 2
  • 13
  • if you need single digit output, then `n % 9 != 0 ? n % 9 : 9` more details are here https://stackoverflow.com/questions/27096670/how-to-sum-digits-of-an-integer-in-java/45780174#45780174 – Vishrant Jul 24 '18 at 21:45

2 Answers2

4

This algorithm depends on n /= 10 being integer division (i.e 5/2 === 2). If you're using Python 3, you'll need to use // so it should probably look like this:

def sumDigits(n):
    sum = 0
    while n > 0: 
        sum += n % 10
        n //= 10  # integer division

    return sum

sumDigits(123)  # 6
Mark
  • 90,562
  • 7
  • 108
  • 148
  • It would be more accurate to say "if you're using Python 3", since the change to the semantics of `/` was part of Python 3 from the beginning. The truncating division operator `//` was introduced in Python 2.2, in 2001. – rici Jul 25 '18 at 03:07
  • Thanks @rici, I wasn't sure when that change happened… – Mark Jul 25 '18 at 15:49
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.