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
To calculate the sum of digits:
- Convert the number to its absolute value (to ignore sign).
- Use a loop to extract each digit using
% 10
. - Add each digit to a running total.
- Divide the number by 10 and repeat until it becomes 0.
- 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