0

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!

Fiery Phoenix
  • 1,156
  • 2
  • 16
  • 30
  • 1
    Do you know what the `%` operator does? Have you considered looking at what `n % 10` is and how `n` changes with each iteration? – Aran-Fey Jul 27 '16 at 09:37
  • Yes, I'm aware of the modulus operator. I was just unsure of its use in this situation. I've tried tracing it on paper but still couldn't quite figure it out. – Fiery Phoenix Jul 27 '16 at 09:38
  • `print(n, sum)` in the loop ? – polku Jul 27 '16 at 09:40
  • `sum([int(i) for i in str(n)])` . Instead of the algorithm. You can try this also. It's out of the conversation i know. I just mentioned an alternative option. – Rahul K P Jul 27 '16 at 09:58

1 Answers1

9

You should understand 2 things:

  1. n % 10 give you the rightmost digit of a number. For example: 123 % 10 = 3
  2. n // 10 remove the rightmost digit of a number. For example: 123 // 10 = 12

so if you repeat that process you get the desired result

Graham
  • 7,431
  • 18
  • 59
  • 84
Ohad Eytan
  • 8,114
  • 1
  • 22
  • 31
  • Perfect, thanks a bunch! I certainly didn't know that. – Fiery Phoenix Jul 27 '16 at 09:44
  • 1
    It does so for numbers represented in the decimal system (base 10), so for any base b (integer > 1) and number n represented in the system with base b the operation n % b yields the rightmost digit and n //= b removes the rightmost digit through augmented integer division. In Python 2 codes sometimes also n /= b may be found. – Dilettant Jul 27 '16 at 10:11