--- Difficulty: Basic Source: 160 Days of Problem Solving (BONUS PROBLEMS π) Tags: - Number Theory - Mathematical - Algorithms --- # π _2. Repetitive Addition of Digits_ π§ The problem can be found at the following link: [Problem Link](https://www.geeksforgeeks.org/batch/gfg-160-problems/track/array-bonus-problems/problem/repetitive-addition-of-digits2221) ## π‘ **Problem Description:** You are given a positive integer `n`. You need to repeatedly add all the digits of `n` to create a new number. Perform this operation until the resultant number has only one digit. Return the final number obtained after performing the given operation. ## π **Example Walkthrough:** **Input:** ``` n = 1234 ``` **Output:** ``` 1 ``` **Explanation:** - Step 1: 1 + 2 + 3 + 4 = 10 - Step 2: 1 + 0 = 1 **Input:** ``` n = 5674 ``` **Output:** ``` 4 ``` **Explanation:** - Step 1: 5 + 6 + 7 + 4 = 22 - Step 2: 2 + 2 = 4 **Input:** ``` n = 9 ``` **Output:** ``` 9 ``` **Explanation:** Since 9 is already a single-digit number, return 9. ### **Constraints:** - $1 \leq n \leq 10^9$ ## π― **My Approach:** This problem revolves around the **digital root** concept in number theory. The process of repetitive digit addition can be optimized without manually summing digits repeatedly. The result of this process is equivalent to `n % 9` with some edge cases: 1. **Digital Root Observation:** - If `n == 0`, the result is `0`. - If `n % 9 == 0` and `n > 0`, the result is `9`. - Otherwise, the result is `n % 9`. This allows us to calculate the final single-digit number in constant time. ## π **Time and Auxiliary Space Complexity** - **Expected Time Complexity:** O(1), as we compute the result directly using mathematical operations. - **Expected Auxiliary Space Complexity:** O(1), as no extra space is used. ## π **Solution Code** ## Code (Cpp) ```cpp class Solution { public: int singleDigit(int n) { return (n == 0) ? 0 : (n % 9 == 0 ? 9 : n % 9); } }; ``` ## Code (Java) ```java class Solution { public int singleDigit(int n) { return (n == 0) ? 0 : (n % 9 == 0 ? 9 : n % 9); } } ``` ## Code (Python) ```python class Solution: def singleDigit(self, n): return 0 if n == 0 else (9 if n % 9 == 0 else n % 9) ``` ## π― Contribution and Support: For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: [Any Questions](https://www.linkedin.com/in/patel-hetkumar-sandipbhai-8b110525a/). Letβs make this learning journey more collaborative! β If you find this helpful, please give this repository a star! β ---