3 Comments

  1. Garrison

    This is incorrect. It should be
    If(n<10){
    return n;
    }
    else{
    return n%10+sum(n/10);
    }
    The way you have it does 1/10 which truncates making the last call a logical error. The first digit is never accounted for and
    always equal to zero with the way you have it. Your method will return 5 instead of 6.

    Reply

    • The solution provided in the article is correct.

      For the last call, n%10, will result in 1 and n/10 will be 0.

      Here is how the values will be at each step of the recursion :

      n%10 = 3
      n/10 = 12

      n%10 = 2
      n/10 = 1

      n%10 = 1
      n/10 = 0

      sum = 3+2+1 = 6

      Reply

Leave a Reply.. code can be added in <code> </code> tags