Search code examples
pythonalgorithmsum-of-digits

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!


Solution

  • 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