4/15 digit_sum


#1

Hello folks,

I was having trouble with this excercise and checked out the hint for a guide. It suggests to turn the digit into a string, itirate over the characters of the now converted string and add the substrings. Finishing with the reconvertion into and integer.

I resolved it this way

def digit_sum(n):
total = 0
for x in str(n):
total += int(x)
return total

It works perfectly, but I don’t understand the point of going through the convertion and reconvertion. Isn’t there a way to add the digits of a number without turning them into a string?


#2

integers aren’t iterable, that is the problem. Isn’t there a hint in the lesson which suggest an advance solution? it doesn’t involve conversion, it used to be there


#3

Thank you! I didn’t remember that concept. Yes, there is another hint that says:

If you’re looking for a challenge, try this: to get the rightmost digit of a number, you can modulo (%) the number by 10. To remove the rightmost digit you can floor divide (//) the number by 10. (Don’t worry if you’re not familiar with floor division—you can look up the documentation here. Remember, this is a challenge!)

Honestly, I’ve looked up the documentation and didn’t understand it. If you could help me I would really appreciate it.


#4

the documentation only covers floor division, do you not understand floor division?

The tricky bit is to get this solution to work, this is programming (solving a problem)

What are the steps needed do you think?


#5

Yeah, I’m not quite sure if I understood floor division right and how it would be useful for the solution.

What I could infer from what I read is that it divides a number by another, and if the quotient of the division is floated, it doesn’t take into consideration the decimals.

e.g. 10//3= 3

Is that correct?


#6

yes, and that combined with the modulo operator and a loop should be enough.


#7

Thank you, I got it. So i moudulo the number by 10 so that e.g the number 1234 , spares the 4 and use floor division to get that number seperated 123 - 4


#8

then all that is needed is a loop and add them to a total


#9

Great! I could work it out, this is the result:

def digit_sum(n):
total = 0
while n != 0:
total += n % 10
n = n // 10
return total

Thank you! :slight_smile:


#10

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