
Problem
Solution
Submissions
Sum of Digits of a Given Number Recursively
Certification: Intermediate Level
Accuracy: 75%
Submissions: 4
Points: 5
Write a Python function to compute the sum of digits of a given integer using recursion.
Example 1
- Input: num = 123
- Output: 6
- Explanation:
- Step 1: Apply recursive function to 123.
- Get the last digit: 123 % 10 = 3
- Remove the last digit: 123 // 10 = 12
- Recursively calculate the sum of digits of 12
- Step 2: Apply recursive function to 12.
- Get the last digit: 12 % 10 = 2
- Remove the last digit: 12 // 10 = 1
- Recursively calculate the sum of digits of 1
- Step 3: Apply recursive function to 1.
- Get the last digit: 1 % 10 = 1
- Remove the last digit: 1 // 10 = 0
- Since we've reached 0, return 1
- Step 4: Combine the results: 3 + (2 + 1) = 3 + 3 = 6.
- Step 5: Return 6 as the sum of digits.
- Step 1: Apply recursive function to 123.
Example 2
- Input: num = 9875
- Output: 29
- Explanation:
- Step 1: Apply recursive function to 9875.
- Get the last digit: 9875 % 10 = 5
- Remove the last digit: 9875 // 10 = 987
- Recursively calculate the sum of digits of 987
- Step 2: Apply recursive function to 987.
- Get the last digit: 987 % 10 = 7
- Remove the last digit: 987 // 10 = 98
- Recursively calculate the sum of digits of 98
- Step 3: Apply recursive function to 98.
- Get the last digit: 98 % 10 = 8
- Remove the last digit: 98 // 10 = 9
- Recursively calculate the sum of digits of 9
- Step 4: Apply recursive function to 9.
- Get the last digit: 9 % 10 = 9
- Remove the last digit: 9 // 10 = 0
- Since we've reached 0, return 9
- Step 5: Combine the results: 5 + (7 + (8 + 9)) = 5 + (7 + 17) = 5 + 24 = 29.
- Step 6: Return 29 as the sum of digits.
- Step 1: Apply recursive function to 9875.
Constraints
- 0 <= number <= 10^9
- Time Complexity: O(log n) where n is the number
- Space Complexity: O(log n) due to recursion stack
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use modulo and integer division to extract digits: number % 10 and number // 10
- Base case: if the number is 0, return 0.
- Recursive case: return the last digit plus the sum of the remaining digits.