0
public static int sumDigits (int n) {
  if(n < 10)
    return n;
  else
    return n%10 + sumDigits (n/10);
}

This method is used to calculate the sum of the digits in a number recursively, but I do not understand it? What is the purpose of n%10???

Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
LipstickQueen
  • 19
  • 1
  • 1
  • 3
  • n%10 returns the rest of a division by 10. example 5%10 would be 5 and 13%10 would be 3 – XtremeBaumer May 15 '17 at 09:30
  • 1
    Possible duplicate of [What's the syntax for mod in java](http://stackoverflow.com/questions/90238/whats-the-syntax-for-mod-in-java) – Sergey May 15 '17 at 09:31
  • Possible duplicate of [Understanding The Modulus Operator %](http://stackoverflow.com/questions/17524673/understanding-the-modulus-operator) – Tom May 15 '17 at 09:33
  • Do be aware that recursion is neither ideal nor necessary to solve this problem. Treat this example as an academic exercise only, not as a good real-world solution. IMHO. – Kevin Anderson May 15 '17 at 09:39

4 Answers4

7

n%10 means modulus of 10. This is used to get last digit.

Let's say your number is 12345

12345 % 10 means remainder when 12345 is divided by 10, which gives you 5.

Thereafter when you perform (n/10) you get 1234 (all the numbers except the least significant digit that you got in previous step).

Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
3

n%10 gives you the least significant digit of n by calculating the remainder of dividing the number by 10.

Hence, the method returns the sum of the least significant digit and the sum of digits of n/10 (which is the number that contains all the digits of n except of the least significant digit).

Eran
  • 387,369
  • 54
  • 702
  • 768
2

n%10 means the modulus of 10, that is the remainder you get when you divide with 10. Here it is used to get each digit.

Example:

Say your number is n = 752.

n%10 = 2, n/10 = 75

So you add 2 to the sumDigits(75)

Now, n%10 = 75%10 = 5. This is the digit to be added and so on, till your n >= 10. When it is < 10, you have a single digit that you just need to return as it is, as that is only the sum of digits in that single-digit number n.

Stuti Rastogi
  • 1,162
  • 2
  • 16
  • 26
1

% is modulus, so n mod 10, it returns the remainder after n / 10.

if n is 1 to 10, then it will return 1 to 9 and 0 when n is 10.

SPlatten
  • 5,334
  • 11
  • 57
  • 128