Beginner Level

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

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
Returns (int) 6

Example 2

Input
n (int) = 0
Returns (int) 0

Example 3

Input
n (int) = -98
Returns (int) 17

Example 4

Input
n (int) = 1001
Returns (int) 2

Example 5

Input
n (int) = -9999
Returns (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
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.