Be the first user to complete this post
|
Add to List |
319. 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 the sum calculated in step 1.
- If the number is less than 10, return the number.
- See the code and click on the run code button for more understanding.
Output:
Sum of digits in a number 12345 till it become a single digit: 6 Sum of digits in the number 999 till it becomes 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 the remainder.
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