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 trial

Java

Ene Catalin
Ene Catalin
1,931 Points

How 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:

Imgur

Ene Catalin
Ene Catalin
1,931 Points

Yes, I'm familiar with it

1 Answer

Brendan Whiting
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 Points

Here'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