← Back to libraryQuestion 75 of 273
⌨️Java CodingBeginner

Sum of Digits of a Number

📌 Definition:

Add up the digits of a non-negative integer (e.g. 1234 -> 1+2+3+4 = 10).

📖 Detailed Explanation:

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).

💻 Solutions:
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)))
🔑 Key Points:
  • Extract digits with %10 and /10
  • Loop until the number is zero
  • Take absolute value for negatives
  • Recursive form is a common follow-up
🌍 Real-World Example:

Digit sums underpin checksum and validation algorithms (e.g. Luhn for card numbers) — small building blocks of real data validation.

🎯 Scenario-Based Interview Question:

In JavaScript, why must you use Math.floor(n / 10) rather than just n / 10?