TechByteByByte

Sum of Digits of a Number - Java

An easy QA/automation coding interview question: sum of Digits of a Number, with a full Java walkthrough, dry run, and common interviewer follow-ups.

#Loops#Recursion#Math#Easy#Java

Category: Easy | Concepts used: Modulo, integer division, recursion


Problem Statement

Given an integer, find the sum of its individual digits.

Input : 1234       Output: 10   (1+2+3+4)
Input : 7            Output: 7    (single digit)

Examples (with edge scenarios)

#InputOutputWhy
11234101+2+3+4
277Single digit โ€” sum is itself
300Zero has โ€œone digit,โ€ which is 0
4-1236 (or -6?)Negative numbers โ€” clarify: do we sum digit magnitudes only, or keep the sign? Usually digit sums are taken as positive
510001Trailing zeros contribute nothing to the sum

Common Fresher Mistake

MistakeWhat happensFix
Not handling negative numbers%10 on a negative number gives a negative digit, throwing off the sumTake Math.abs(n) first, or work with the negation, before extracting digits
Converting to a String and looping over characters, then treating each char as its ASCII valueOff results, since '5' isnโ€™t the integer 5 โ€” need Character.getNumericValue() or subtract '0'If going the String route, use Character.getNumericValue(ch) or ch - '0' to convert correctly

Before You Code: Clarify the Contract

Before choosing an algorithm, confirm whether zero and negative values are allowed, how large the input can be, and what should happen when an arithmetic result exceeds the chosen Java type. The examples use the contract stated in this article, but an interview answer should say these assumptions aloud.

Analogy: Peeling an Onion

Imagine you have an onion (the number 1234), and you want to count the rings of each layer:

  • The last digit (4) is the outermost layer of the onion.
  • You peel it off using the modulo knife (n % 10), add it to your bowl (sum += 4), and throw away the peeled skin.
  • The remaining onion is now smaller (n / 10 = 123).
  • You repeat this process: peel the outer layer 3, then 2, then 1.
  • When thereโ€™s nothing left of the onion (n = 0), you stop. The bowl now contains the sum of all the peeled layer values!

Intuition

n % 10 peels off the last digit of a number (e.g., 1234 % 10 = 4), and n / 10 (integer division) chops that last digit off, shrinking the number (1234 / 10 = 123). Repeating this โ€” peel off a digit, add it to a running sum, shrink the number โ€” eventually exhausts every digit, one at a time, from right to left.

public class SumOfDigits {
    public static int sumOfDigits(int n) {
        n = Math.abs(n); // handle negative numbers by working with magnitude
        int sum = 0;

while (n > 0) {
            int lastDigit = n % 10;  // peel off the last digit
            sum += lastDigit;
            n = n / 10;               // shrink the number
        }
        return sum;
    }

public static void main(String[] args) {
        System.out.println(sumOfDigits(1234)); // 10
        System.out.println(sumOfDigits(7));      // 7
        System.out.println(sumOfDigits(0));       // 0
        System.out.println(sumOfDigits(-123));     // 6
    }
}

Output:

10
7
0
6

Edge case note: sumOfDigits(0) returns 0 correctly โ€” but only because the loop condition is n > 0. If n starts at exactly 0, the loop never runs, and sum stays at its initial value of 0, which happens to be the right answer here.

Dry Run (n = 1234)

n=1234, sum=0
lastDigit=1234%10=4, sum=0+4=4, n=1234/10=123
lastDigit=123%10=3,  sum=4+3=7, n=123/10=12
lastDigit=12%10=2,   sum=7+2=9, n=12/10=1
lastDigit=1%10=1,    sum=9+1=10, n=1/10=0
n=0 -> loop stops
Final sum = 10

Interviewerโ€™s take

This is exactly the expected solution โ€” itโ€™s the standard, efficient way to extract digits using pure arithmetic, without needing to convert to a String at all. Handling the negative-number edge case with Math.abs() up front is an important detail interviewers watch for.

Follow-up questions you might get:

  • โ€œWhat would happen if you forgot Math.abs()?โ€ โ†’ For n = -123, n % 10 in Java would give -3 (negative remainder), and the loop condition n > 0 would actually never even trigger since n starts negative โ€” so the function would incorrectly return 0 for any negative input without the fix.
  • โ€œCan you do this using recursion?โ€ โ†’ leads to Solution 2.

Solution 2 โ€” Recursive Approach

Intuition

The problem has a natural recursive shape: โ€œsum of digits of nโ€ = โ€œlast digit of nโ€ + โ€œsum of digits of the rest of n (with the last digit removed).โ€ Each recursive call handles one digit, until nothingโ€™s left.

public class SumOfDigitsRecursive {
    public static int sumOfDigits(int n) {
        n = Math.abs(n);
        if (n == 0) {
            return 0; // base case: no digits left to add
        }
        return (n % 10) + sumOfDigits(n / 10); // last digit + sum of the rest
    }

public static void main(String[] args) {
        System.out.println(sumOfDigits(1234)); // 10
        System.out.println(sumOfDigits(7));      // 7
    }
}

Output:

10
7

Dry Run (n = 123)

sumOfDigits(123) = 3 + sumOfDigits(12)
sumOfDigits(12)  = 2 + sumOfDigits(1)
sumOfDigits(1)   = 1 + sumOfDigits(0)
sumOfDigits(0)   = 0  (base case)

Unwinding: 1+0=1, 2+1=3, 3+3=6
Final: 6  (1+2+3 = 6)

Interviewerโ€™s take

Equally valid โ€” same logic as the iterative version, just expressed recursively. Good to mention as an alternative; some interviewers specifically like to see if you can convert between iterative and recursive thinking for the same problem.

Follow-up questions you might get:

  • โ€œWhatโ€™s the space complexity difference between iterative and recursive here?โ€ โ†’ Iterative uses O(1) extra space; recursive uses O(d) space for the call stack, where d is the number of digits (usually small, so not a big concern here, but worth mentioning).

๐Ÿ“Š Visual Flowchart

graph TD
    Start["Input Number n"] --> Absolute["n = Math.abs(n)"]
    Absolute --> Init["Initialize sum = 0"]
    Init --> Loop{"n > 0?"}
    Loop -->|Yes| Mod["lastDigit = n % 10"]
    Mod --> Add["sum += lastDigit"]
    Add --> Div["n = n / 10"]
    Div --> Loop
    Loop -->|No| End["Return sum"]

Final Verdict โ€” Which Solution Should You Give?

  • Both solutions are considered good. Solution 1 (iterative) is the more commonly expected default; Solution 2 (recursive) is a nice alternative to mention.
  • The real differentiator is correctly handling negative numbers and zero โ€” call these out explicitly regardless of which version you write.

Quick Recap

ApproachTimeSpaceInterview Signal
Iterative (% and /)O(d) โ€” d = number of digitsO(1)Preferred default
RecursiveO(d)O(d) call stackGood alternative
Author
TechByteByByte Editorial Team
Reviewed by
TechByteByByte Admin
Published
Last reviewed