basics · beginner · ~10 min
Loop with `n % 10` and `n /= 10`.
Add up the decimal digits of an integer (ignoring its sign).
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.
A single signed int n (may be negative).
Returns the sum of the digits of |n| as an int.
digit_sum(123) -> 6 (1 + 2 + 3)
digit_sum(0) -> 0
digit_sum(-456) -> 15 (4 + 5 + 6)
digit_sum(9999) -> 36
n == 0 returns 0.INT_MIN is special: -INT_MIN overflows, so compute the magnitude via unsigned rather than calling abs.Digit-sum is the kernel of Luhn checksums, ISBN validation, and many small checksums in protocols.
A single signed int n.
The sum of the decimal digits of |n|, as an int.
No string conversion. Take the magnitude via unsigned to handle INT_MIN.
int digit_sum(int n) { /* TODO */ return 0; }
Forgetting abs(n) — negative % gives negative digits in C.
n == 0 → 0. n == INT_MIN — abs is undefined; cast to unsigned first.
O(log10 n).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.