Get the Sum of Digits in a number till it become a single digit

Objective – Given a number, Write a program to get the sum of digits in a number till it become a single digit.

Example:

N = 999 -> 9+9+9 = 27-> 2+7 = 9
N = 789 -> 7+8+9= 24-> 2+4 = 6

Approach:

Recursion

  • Find the sum of all digits.
  • Make a recursive call with sum calculated in step 1.
  • If number is less than 10, return number.
  • See the code and click on run code button for more understanding.

Code:

public class SumOfDigitsTillSingleDigitRecursion {
static int findSum(int N){
if(N<10)
return N;
int sum = 0;
while(N>0){
sum += N%10;
N = N/10;
}
return findSum(sum);
}
public static void main(String[] args) {
int N = 12345;
int result = findSum(N);
System.out.println("Sum of digits in a number " + N + " till it become a single digit: " + result);
N = 999;
result = findSum(N);
System.out.println("Sum of digits in a number " + N + " till it become a single digit: " + result);
}
}

Output:

Sum of digits in a number 12345 till it become a single digit: 6
Sum of digits in a number 999 till it become a single digit: 9

Tricky Approach:

  • If number is 0, return 0.
  • Find remainder of number with 9. (number%9).
  • If remainder is 0, return 9 else return remainder.

Code:

public class SumOfDigitsTillSingleDigitTricky {
static int findSum(int N){
if(N==0)
return N;
int remainder = N%9;
if(remainder==0)
return 9;
else
return remainder;
}
public static void main(String[] args) {
int N = 12345;
int result = findSum(N);
System.out.println("Sum of digits in a number " + N + " till it become a single digit: " + result);
N = 999;
result = findSum(N);
System.out.println("Sum of digits in a number " + N + " till it become a single digit: " + result);
N = 111;
result = findSum(N);
System.out.println("Sum of digits in a number " + N + " till it become a single digit: " + result);
}
}

Output:

Sum of digits in a number 12345 till it become a single digit: 6
Sum of digits in a number 999 till it become a single digit: 9
Sum of digits in a number 111 till it become a single digit: 3