How to calculate Sum of Digits using Recursion in Java [Example]

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 the rest of the 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 step your program approaches to result and problems become 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 the last digit of an integral number. You can use the modulo operator to do that, number%10 always returns the last digit.

For more coding problems from interviews, you can also check the Cracking the Coding Interview: 150 Programming Questions and Solutions, one of the best collections of programming questions from reputed companies like Google, Microsoft, Amazon, and Facebook.




Sum of Digits of a Number using Recursion

Here is my complete solution and code sample to solve this problem. I am using the main method to test the code but I encourage you to write JUnit test to test your code. Using unit tests to check your program is a good development practice, initially, it takes some time but once you get used to it, it's a cakewalk. This is my personal experience that writing a JUnit test triggers your thought process and think-through ability, which eventually results in better code.

In this example, we are also using two methods to implement the recursive algorithm, a common practice. Since sometimes the recursive method carries the current state of the program in function parameters itself, it's better to write a public method to accept input from the client and a private method to do the work.

As I said before, if you need more coding problems from interviews, you can also check the Cracking the Coding Interview: 150 Programming Questions and Solutions, one of the best collections of programming questions.


How to calculate the sum of digits using recursion

/**
 * Java program to find sum of digits using recursion.
 * 
 * @author WINDOWS 8
 */

 class SumOfDigitSolution {

  public static void main(String args[]) {
  
  System.out.printf("Sum of digit of number % d using recursion is : %d %n",
  343, sumOfDigit(343));
  System.out.printf("Sum of digit of using recursion for number %d is : %d %n",
  287, sumOfDigit(287));
  System.out.printf("Recursive Sum of digit of number % d is : %d %n",
  657, sumOfDigit(647));
  System.out.printf("Sum of digit of number % d using recursion is : %d %n",
  1001, sumOfDigit(1001));
  }

  /*
  * public method to calculate sumOfDigit using recursion 
  * it calls a private method which actual does the work
  */
  public static int sumOfDigit(int input){
  return sumOfDigitUsingRecursion(input, 0);
  }
 
  /*
  * Java method to return sum of digit using recursion
  * input 125
  * output 8
  */
  private static int sumOfDigitUsingRecursion(int number, int sum) {
  if (number == 0) {
  return sum;
  }
  sum += number % 10;
  return sumOfDigitUsingRecursion(number / 10, sum);
  }
}

Output
Sum of digit of number 343 using recursion is : 10 
Sum of digit of using recursion for number 287 is : 17 
Recursive Sum of digit of number 657 is : 17 
Sum of digit of number 1001 using recursion is : 2 

and here is the JUnit test class to test our sum of digit code. It tests the method for zero, positive and negative numbers, and boundary cases e.g. Integer.MAX_VALUE and Integer.MIN_VALUE.

Recursion in Java - Sum of digit example



You can also add as many tests as you want. Here we are also using the static import feature of Java 1.5 to import the static assert method e.g. assertEquals(), which you can see that we are using that as a regular member of the class itself.

import static org.junit.Assert.*;
import org.junit.Test;
/*
 * JUnit test cases to test our code
 */
public class Testing{
  
  @Test
  public void sumOfDigit(){
  assertEquals(6, SumOfDigitSolution.sumOfDigit(123));
  assertEquals(46, SumOfDigitSolution.sumOfDigit(Integer.MAX_VALUE));
  assertEquals(0, SumOfDigitSolution.sumOfDigit(0));
  assertEquals(-6, SumOfDigitSolution.sumOfDigit(-123));
  assertEquals(-47, SumOfDigitSolution.sumOfDigit(Integer.MIN_VALUE));
  
  }
}

That's all about how to solve this coding problem of calculating the sum of digits in a given number using recursion in Java. Though recursion has several drawbacks like hard to read, write and StackOverflow error, there is a situation where it fits nicely. Also, there is a couple of JVM language like Scala, which optimizes tail recursion to avoid StackOverFlowError, but Java doesn't do that. That's why to avoid using recursion in production code.

2 comments:

  1. Very well explained!

    ReplyDelete
  2. public class RecSumOfDigit {

    public static void main(String[] args) {
    int a=123456;
    int sod=SumofDig(a);
    System.out.print(sod);
    }

    private static int SumofDig(int a) {
    if(a==0)
    return 0;
    else
    {

    return (a%10)+SumofDig(a/10);
    }
    }

    }

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.