1

Could anyone explain how does this method works.

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

I input n = 15 and it get a 6 but I don't understand how the method works. please help. thank you.

Ace Shafiq
  • 27
  • 1
  • 7

5 Answers5

2

The method calculates the sum of the digits.

If the n is smaller than 10, you simply return n (since the sum of digits of a single digit number is the number itself).

Otherwise you add the least significant digit (that's n % 10) to the sum of digits of the number n / 10 (which is calculated recursively).

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

It goes like this:

calculate(15);

evaluates to

15%10 + calculate(1);

evaluates to

5 + 1;

which in the end; sums up to 6.

In other words; the above is an recursive approach to sum all the digits in a number. You could easily re-write this using a simple loop to avoid the recursion construct.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

For n = 15 , here is how it works

15/10 > 0 , so the else condition is executed.

15%10 + calculate(15/10) i.e 5 + calculate(1).

The method is called again for n = 1;

Since 1/10 == 0 , 1 is returned

This 1 is then added to 5.

Therefore answer is 6.

So what this function does is return the sum of the digits that make up the number.

Dishonered
  • 8,449
  • 9
  • 37
  • 50
0

It cuts off the most right digit and moves on recursively with the rest of the number. (line 5) If we have only one digit left (line 2), it is also added to the sum and the algorithm ends. (line 3)

Matthias Sommer
  • 1,070
  • 13
  • 28
0

In this example there is a if else condition so on the basis of input parameter there are 2 conditions '

-Firstly it checks in the if condition (n/10 == 0) .

-Consider your input as n=15.

  • now it checks if (n/10 == 0) i.e 15/10==0 which is false because 15/10=5 which is not equal to 0.

-As the condition is false it moves to else block where condition is to return (n % 10 + calculate(n/10)

i.e. (15%10 +15/10)==5+1==6 -So the return is 6.

Amit Gujarathi
  • 1,090
  • 1
  • 12
  • 25