Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialEne Catalin
1,931 PointsHow does the sumDigits method work?
The program calculates the sum of the digits of an integer, but I don't understand how the sumDigits method works:
Ene Catalin
1,931 PointsYes, I'm familiar with it
1 Answer
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsHere's how it works:
- initializes a
sum
variable set a 0 - finds the value of the last digit with
n % 10
. Modulus returns the remainder of a division, so the remainder of dividing by ten will return any value from 0-9 that's in the last position. So if n was 176, 176 / 10 would give us 17 remainder 6, so that would give us the number 6 - we add that number to the sum
- we divide the original number by 10 so that we can move on to the next digit. So 170 divided by 10 gives us 17, and now in the next iteration, 17 % 10 will gives us 7. So this will keep running until we've summed up all the digits
Ene Catalin
1,931 PointsThanks a lot!
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsBrendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsAr you familiar with the modulus operator?