Sunday 23 August 2015

Sum of digits using recursion

For a given number n, find sum of digits in n.
For example, if n = 97650 (sum = 9 + 7 + 6 + 5 = 27)
public class SumOfDigits {

 public static int getSumOfDigits(int num) {
  if (num < 0)
   return getSumOfDigits(-num);

  if (num < 10)
   return num;

  return num % 10 + getSumOfDigits(num / 10);

 }
}


Following is the junit test case for above program.

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class SumOfDigitsTest {

 @Test
 public void test1() {
  assertEquals(SumOfDigits.getSumOfDigits(1), 1);
  assertEquals(SumOfDigits.getSumOfDigits(12), 3);
  assertEquals(SumOfDigits.getSumOfDigits(123), 6);
  assertEquals(SumOfDigits.getSumOfDigits(1234), 10);

  assertEquals(SumOfDigits.getSumOfDigits(-1), 1);
  assertEquals(SumOfDigits.getSumOfDigits(-12), 3);
  assertEquals(SumOfDigits.getSumOfDigits(-123), 6);
  assertEquals(SumOfDigits.getSumOfDigits(-1234), 10);
 }
}


No comments:

Post a Comment