How to calculate Sum of Digits using Recursion in Java
This is the
second part of our article to solve this coding interview question, how
to find the sum of digits of an integer number in Java. In the first part,
we have solved this problem without using recursion i.e. by using a while loop
and in this part, we will solve it by using recursion. It's good to know
different approaches to solving the same problem, this will help you to do well
on coding interviews. While finding a recursive algorithm, always search for a
base case, which requires special handling. Once you find the base case, you
can easily code the method by delegating rest of processing to the method
itself, i.e. by using recursion. In this problem, the base case is when
the number becomes zero, at that time our program is complete and we return the
sum of digits of given number. Another property of a recursive algorithm is that
with each passing steps your program approaches to result and problems become
shorter.