## Java Program to Add Digits Until the Number Becomes a Single Digit NumberIn this section, we will create Java programs that
Suppose, 7 + 6 + 3 + 4 + 5 = 25 Further, we will add 2 and 5. 2 + 5 = 7 We get 7 as a single-digit number. ## Brute Force Approach- Calculate the sum of all digits.
- Make a recursive call with the sum (calculated in the above step).
- If the number is less than 10, return the number.
Let's implement the above logic in a Java program.
The sum of digits is: 1 We can also solve the above problem without using any loop and recursion. The approach is as follows: In this approach, first, check if the number is divisible by 9 or not. If divisible, add the digits together and check if the sum is divisible by the number 9 or not. If divisible, the number is divisible by 9, else not. For example, We observe that if a number (n) is divisible by 9, then sum up its digit until the sum becomes a single digit which is always 9. For example: n = 2880 Sum of digits = 2 + 8 + 8 + 0 = 18 The number 18 further can be added to form a single digit number. 18 = 1 + 8 = 9 The answer is always 9, if a number has the form like 9x. If the number is of the form 9x+k A number can be of the form 9x or 9x + k. For the first case, the answer is always 9. For the second case, the answer is always k which is the remainder. - If number is 0, return 0.
- Find remainder of number with 9. (number%9).
- If remainder is 0, return 9 else return remainder.
Let's implement the above approach in a Java program.
The sum of digits is: 2 The above approach solves the problem in |

For Videos Join Our Youtube Channel: Join Now

- Send your Feedback to [email protected]