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

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

Ar you familiar with the modulus operator?

Yes, I'm familiar with it

1 Answer

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

Thanks a lot!