CC-19 : Find sum of digits of number.
Description:
Given an input num N find sum of its digits.
Test cases and expected outputs:
| Input Parameters |
Expected outputs |
| Number: 5432
|
Sum of digits: 14
|
| Number: 678
|
Sum of digits: 21
|
Pseudocode:
sumDigits(N):
| If N==0:
return 0.
|
| Else :
o Return number calculated by adding num%10 to return value from sumDigits(num/10).
|
Code:
public int sumDigits(int num){
if (num == 0) {
return 0;
}else {
int sum= num%10 + sumDigits(num/10);
return sum;
}
}
Click here to download and run code and test cases !
Below fully running code can be copied and run on Eclipse or other Java IDEs. Refer the classname in code below. If the class name below is "A", save the code below to a file named A.java before running it.
Be sure to try your own test cases to enhance your understanding !
You can also tweak the code to optimize or add enhancements and custom features.
public class RecursionSumOfDigits {
public int sumDigits(int num){
if (num == 0) {
return 0;
}else {
int sum= num%10 + sumDigits(num/10);
return sum;
}
}
public static void main(String[] args) {
/************************
Test cases given below:
**********************/
int retVal;
try {
RecursionSumOfDigits rcn=new RecursionSumOfDigits();
int num=5432;
retVal=rcn.sumDigits(num);
System.out.println("Number: "+num);
System.out.println("Sum of digits: "+retVal);
System.out.println();
num=678;
retVal=rcn.sumDigits(num);
System.out.println("Number: "+num);
System.out.println("Sum of digits: "+retVal);
}catch (Exception exception) {
System.out.print("Exception: "+ exception);
exception.printStackTrace();
}
}
}