Final answer:
The recursive method sumOfDigits calculates the sum of the digits of an integer by handling negatives, base cases, and the recursive step of adding the last digit to the sum of the remaining digits.
Step-by-step explanation:
The sumOfDigits method can be implemented recursively by following these steps:
- Check if the given number x is less than 0. If so, multiply it by -1 to make it positive since we are ignoring the minus sign.
- If the number x is less than 10, return x because it's the last digit.
- Otherwise, return x % 10 (which gives the last digit) plus the result of a recursive call to sumOfDigits with x / 10 (which removes the last digit).
Here is an implementation in code:
int sumOfDigits(int x) {
if (x < 0) {
x = -x;
}
if (x < 10) {
return x;
}
return x % 10 + sumOfDigits(x / 10);
}