basics · beginner · ~10 min

Sum of decimal digits

Loop with `n % 10` and `n /= 10`.

Challenge

Add up the decimal digits of an integer (ignoring its sign).

Task

Implement int digit_sum(int n) that returns the sum of the decimal digits of the absolute value of n. Extract digits with % 10 and /= 10 in a loop — do not convert to a string.

Input

A single signed int n (may be negative).

Output

Returns the sum of the digits of |n| as an int.

Example

digit_sum(123)    ->   6     (1 + 2 + 3)
digit_sum(0)      ->   0
digit_sum(-456)   ->   15    (4 + 5 + 6)
digit_sum(9999)   ->   36

Edge cases

  • n == 0 returns 0.
  • For negatives, take the magnitude first. INT_MIN is special: -INT_MIN overflows, so compute the magnitude via unsigned rather than calling abs.

Rules

  • No string conversion — pure arithmetic.

Why this matters

Digit-sum is the kernel of Luhn checksums, ISBN validation, and many small checksums in protocols.

Input format

A single signed int n.

Output format

The sum of the decimal digits of |n|, as an int.

Constraints

No string conversion. Take the magnitude via unsigned to handle INT_MIN.

Starter code

int digit_sum(int n) { /* TODO */ return 0; }

Common mistakes

Forgetting abs(n) — negative % gives negative digits in C.

Edge cases to handle

n == 0 → 0. n == INT_MIN — abs is undefined; cast to unsigned first.

Complexity

O(log10 n).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.