This is the second part of our article to solve this coding interview question, how to find sum of digits of a integer number in Java. In
first part, we have solved this problem without using recursion i.e. by using while loop and in this part we will solve it by using recursion. It's good to know different approaches to solve the same problem, this will help you to do well on coding interviews. While finding recursive algorithm, always search for base case, which requires special handling. Once you find the base case, you can easily code the method by delegating rest of processing to method itself, i.e. by using recursion. In this problem, 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 becomes shorter. For example in this coding problem, after each call one digit from the number is reduced. So if you provide 5 digit number then it will require five steps to complete. One key thing you need to know to solve this problem is the trick to get last digit of an integral number. You can use
modulo operator to do that,
number%10 always return the last digit.