DSA problem
Sum of Digits of a Number
Given an integer N, compute the sum of its digits.
This is the simplest application of digit extraction: take the last digit with N % 10, add it to a running total, then drop it with integer division, repeating until N reaches 0. Take the absolute value first so negative inputs are handled correctly.
Digit sums power real algorithms: repeatedly summing digits gives a digital root, used in check-digit schemes like Luhn's algorithm (credit-card validation) and ISBN validation. A neat fact - the digital root of any multiple of 9 is always 9 - connects digit sums to modular arithmetic.
Examples
Example 1
Input:
N = 9876Output:
30Explanation: 9 + 8 + 7 + 6 = 30.
Constraints
- -10^9 <= N <= 10^9
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.