Add up the digits of a non-negative integer (e.g. 1234 -> 1+2+3+4 = 10).
Repeatedly take the last digit with % 10, add it to a running sum, and drop it with integer division by 10 until the number is zero. O(number of digits). A recursive variant sums digit + sumDigits(n / 10).
public static int sumDigits(int n) {
n = Math.abs(n);
int sum = 0;
while (n != 0) { sum += n % 10; n /= 10; }
return sum;
}function sumDigits(n) {
n = Math.abs(n);
let sum = 0;
while (n !== 0) { sum += n % 10; n = Math.floor(n / 10); }
return sum;
}def sum_digits(n):
return sum(int(d) for d in str(abs(n)))Digit sums underpin checksum and validation algorithms (e.g. Luhn for card numbers) — small building blocks of real data validation.
In JavaScript, why must you use Math.floor(n / 10) rather than just n / 10?