Implement the method sumDigits that takes an integer as input and returns the sum of its digits.

Beginner Level
Loop Math

You need to write a function that calculates the sum of all digits in a given integer.
The function should ignore the sign of the number — treat negative numbers as positive.

For example:

  • sumDigits(123)1 + 2 + 3 = 6
  • sumDigits(-45)4 + 5 = 9
Example 1
Input:
n (int) = 123
Return:
(int) 6
Example 2
Input:
n (int) = 0
Return:
(int) 0
Example 3
Input:
n (int) = -98
Return:
(int) 17
Example 4
Input:
n (int) = 1001
Return:
(int) 2
Example 5
Input:
n (int) = -9999
Return:
(int) 36

To calculate the sum of digits:

  1. Convert the number to its absolute value (to ignore sign).
  2. Use a loop to extract each digit using % 10.
  3. Add each digit to a running total.
  4. Divide the number by 10 and repeat until it becomes 0.
  5. Return the total.

Pseudocode:

Function sumDigits(n):
    n ← absolute value of n
    total ← 0
    While n > 0:
        digit ← n mod 10
        total ← total + digit
        n ← n div 10
    Return total
Run your code to see the result.