Difficulty | Source | Tags | |||
---|---|---|---|---|---|
Basic |
160 Days of Problem Solving (BONUS PROBLEMS 🎁) |
|
The problem can be found at the following link: Problem Link
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.
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.
$1 \leq n \leq 10^9$
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:
- Digital Root Observation:
- If
n == 0
, the result is0
. - If
n % 9 == 0
andn > 0
, the result is9
. - Otherwise, the result is
n % 9
.
- If
This allows us to calculate the final single-digit number in constant time.
- 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.
class Solution {
public:
int singleDigit(int n) {
return (n == 0) ? 0 : (n % 9 == 0 ? 9 : n % 9);
}
};
class Solution {
public int singleDigit(int n) {
return (n == 0) ? 0 : (n % 9 == 0 ? 9 : n % 9);
}
}
class Solution:
def singleDigit(self, n):
return 0 if n == 0 else (9 if n % 9 == 0 else n % 9)
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐