+ 1

Can anyone help me fix this code?

This program is intended to add up digits of a number until the sum is single digit. But it's not working as expected. https://code.sololearn.com/cjHcfS9BIcuk/#

25th Feb 2020, 7:42 PM
Leena
4 Réponses
+ 8
When you do the recursion don't forget that your function has a return value. So just calling calcSum() without actually using the result, is a waste. Fortunately you can easily fix this in line 22. if(sum>9){ return calcSum(sum); }
25th Feb 2020, 7:48 PM
Tibor Santa
Tibor Santa - avatar
+ 5
And in case you want to see a maths trick: public static int calcSum(int n) { if(n % 9 == 0) return 9; else return n % 9; }
25th Feb 2020, 8:04 PM
Schindlabua
Schindlabua - avatar
+ 1
Tibor Santa Thank you! It helped :-)
26th Feb 2020, 3:10 AM
Leena
+ 1
Nice code! I think you should gently mark @Tibor Santa answer like a solution @Leena.
26th Feb 2020, 5:34 AM
Rafael S Valle
Rafael S Valle - avatar