Skip to content

Latest commit

 

History

History
135 lines (91 loc) · 2.81 KB

File metadata and controls

135 lines (91 loc) · 2.81 KB
Difficulty Source Tags
Basic
160 Days of Problem Solving (BONUS PROBLEMS 🎁)
Number Theory
Mathematical
Algorithms

🚀 2. Repetitive Addition of Digits 🧠

The problem can be found at the following link: Problem Link

💡 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)

class Solution {
public:
    int singleDigit(int n) {
        return (n == 0) ? 0 : (n % 9 == 0 ? 9 : n % 9);
    }
};

Code (Java)

class Solution {
    public int singleDigit(int n) {
        return (n == 0) ? 0 : (n % 9 == 0 ? 9 : n % 9);
    }
}

Code (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. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


📍Visitor Count