Digit_sum alternate solution


#1

I honestly could not figure this one out for the life of me. I thought the “solution” would help me figure out what it was asking for, but it seems that most people in the forums used the “converting the integer into a string” method. can someone explain the solution’s method instead?

“Write a function called digit_sum that takes a positive integer n as input and returns the sum of all that number’s digits. For example: digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4 . (Assume that the number you are given will always be positive.)”

def digit_sum(x):
    total = 0
    while x > 0:
        total += x % 10
        x = x // 10
        print x
    return total

I understand the method using strings but what is going on here? I’d just like a step by step explanation :blush:


#2
if x is 1234 then x % 10 is 4

if x is 1234 then x // 10 is 123

We first extract the 1’s digit and add it to the total, then we floor divide (which gives an integer result) by 10 to lob off that digit, and repeat the process until x winds down to 0.


Modulo, or remainder is the remaining integer when we divide one number by another.

   _______
10 ) 1234 | 123
    -1230
   -------
        4    modulo (remainder)

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.