java - sum of Digits through Recursion -


i trying make recursive function should return sum of digits. function should have 1 argument. far have this;

public int sumdigits(int n) {     if(n%10 == n) // last digit remains         return n;      else{         int rightdigit;          rightdigit = n%10; // taking out right digit         return rightdigit + (n/10); // adding on left     } } 

the function works values, 2 digit numbers. gives out odd values numbers 730 comes out 73 when should 10.

i have worked out on paper cant figure out going wrong. appreciated.

you aren't recursing. you've setup base case, when solving problem recursively should have code within function calls function itself.

so you're missing line calls sumdigits, smaller argument.

consider 2 important parts of recursive soutlion:

  1. the base case. end of recursion, @ point recursions begin return, in case creating sum.
  2. the recursion: recursive function call itself, different argument, typically smaller chunk of problem.

note problem fits pretty well: you've got 2 cases in if/else. base case set nicely, in other branch you'll want recurse. should obvious put call sumdigits.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -