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:

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:

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

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

%d bloggers like this: