Given a number n, we need to find the sum of its digits such that:
If n < 10 digSum(n) = n Else digSum(n) = Sum(digSum(n))
Input : 1234 Output : 1 Explanation : The sum of 1+2+3+4 = 10, digSum(x) == 10 Hence ans will be 1+0 = 1 Input : 5674 Output : 4
A brute force approach is to sum all the digits until sum < 10.
Below is the brute force program to find the sum.
There exists a simple and elegant O(1) solution for this too. The ans is given by simply :-
If n == 0 return 0; If n % 9 == 0 digSum(n) = 9 Else digSum(n) = n % 9
How does the above logic works?
If a number n is divisible by 9, then the sum of its digit until sum becomes single digit is always 9. For example,
Let, n = 2880
Sum of digits = 2 + 8 + 8 = 18: 18 = 1 + 8 = 9
A number can be of the form 9x or 9x + k. For the first case, answer is always 9. For the second case, and is always k.
Below is the implementation of the above idea :
This article is contributed by Ayush Khanduri. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Maximum of sum and product of digits until number is reduced to a single digit
- Number of times a number can be replaced by the sum of its digits until it only contains one digit
- Number formed by deleting digits such that sum of the digits becomes even and the number odd
- Count of N-digit numbers having digit XOR as single digit
- Reduce number to a single digit by subtracting adjacent digits repeatedly
- Sum of Digits in a^n till a single digit
- Numbers less than N that are perfect cubes and the sum of their digits reduced to a single digit is 1
- Find third number such that sum of all three number becomes prime
- Finding number of digits in n'th Fibonacci number
- Expected Number of Trials until Success
- Number of days until all chocolates become unhealthy
- Numbers of Length N having digits A and B and whose sum of digits contain only digits A and B
- Add minimum number to an array so that the sum becomes even
- Insert minimum number in array so that sum of array becomes prime
- Check whether a number can be expressed as a product of single digit numbers
- Check if number can be made prime by deleting a single digit
- Minimum value to be assigned to the elements so that sum becomes greater than initial sum
- Largest number less than N with digit sum greater than the digit sum of N
- Minimum digits to be removed to make either all digits or alternating digits same
- Finding n-th number made of prime digits (2, 3, 5 and 7) only