Newbie in Programming - more effecient sumOfDigits
java, performance
Solution
Recursion is not a bad tool at all in Java. Sure, theoretically every function call has a cost, but the JIT compiler is often able to optimize that by itself at runtime and offer a good performance. You should not optimize a function that is clearly written with recursion with another which is more cumbersome without it, except if you really experience problems, but I doubt you'll have any with that code. With experience you'll see that code legibility matters a lot.
To answer your question, the other way to implement what you want is simply to loop until num equals 0 and storing the result of division per 10 in num every time:
int total = 0;
while (num != 0) {
total += num % 10;
num = num / 10;
}
Problem
I came out with this Java code to solve sumOfDigits. ``` public static int sumOfDigits(int num){ if (num == 0){ return 0; } return num%10+ sumOfDigits(num/10); } ``` Well I know this works, but I'm hoping anyone would share insights or materials(some formal terms/knowledge) on how to improve code efficiency, as I know Java does not support recursion that well.