0
What went wrong
Can anyone one suggest me what the problem with my logic , i used recultion to get the sum of digits of number ,it is supposed to show 6 but showing 3 https://code.sololearn.com/cvmom9HfMkZS/?ref=app
2 Respuestas
+ 1
It is recursion so you are getting initial call su value. Not the last one. It is missing..
Try this :
public int sum(int num,int su){
su+=num%10;
if(num != 0)
return sum(num/10,su);
return su;
}
+ 2
public class SumOfDigRecultion
{
public int sum(int num,int su){
return (num != 0)?sum(num/10,su+num%10):su;
}
public static void main(String[] args) {
int num = 123;
SumOfDigRecultion sd = new SumOfDigRecultion();
int res = sd.sum(num,0);
System.out.println(res);
}
}
//Change the value of num to get your respective output.