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

24th Sep 2022, 8:35 AM
Shivam Shiva
Shivam Shiva - avatar
2 Respostas
+ 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; }
24th Sep 2022, 10:51 AM
Jayakrishna 🇮🇳
+ 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.
24th Sep 2022, 9:44 AM
Just Some Random Guy
Just Some Random Guy - avatar