Start learning free

LESSON 211 OF 285 · WHILE LOOPS - CHALLENGES

Digit Sum in Java: A While Loop with % and /

Practice Read the full explanation

Given a non-negative integer n, return the sum of its digits.

The digits are the figures from 0 to 9 that n is written with: 472 has the digits 4, 7 and 2. If n is 0, the sum is 0.

The last digit of a number is the remainder of its division by 10 (472 % 10 is 2), and dividing by 10 without the remainder removes that digit (472 becomes 47).

 

Example 1:

Input: n = 472
Output: 13
Explanation: Taking the digits from the right: 2 + 7 + 4 = 13.

Example 2:

Input: n = 1005
Output: 6
Explanation: 5 + 0 + 0 + 1 = 6. The zeros add nothing.

Example 3:

Input: n = 7
Output: 7
Explanation: A number with one digit is its own digit sum.

 

Constraints:

  • 0 <= n <= 109
STEP 1 OF 5
    Ctrl + Enter to check

    JAVA · WHILE LOOPS - CHALLENGES

    Digit Sum in Java, explained

    Problem overview

    The method digitSum receives a non-negative integer n up to one billion and returns the sum of its digits. For n = 472 the digits are 4, 7 and 2, so the answer is 13. For 1005 it is 6, because the zeros add nothing, and a single digit such as 7 is its own sum. For 0 the sum is 0.

    Approach: peel off the last digit

    Two integer operations take a number apart without converting it to text:

    • n % 10 is the remainder after dividing by 10, which is the last digit: 472 % 10 is 2.
    • n / 10 with two int values drops the remainder, which removes the last digit: 472 / 10 is 47.

    Repeat both on the shrinking number. Each pass adds one digit to a running total and removes it from n. When n reaches 0, every digit has been counted.

    Step by step

    1. Create total as an int starting at 0. It holds the sum so far.
    2. Write a while (n > 0) loop. It runs once per digit. For n = 0 it never runs, and the answer 0 is already correct.
    3. Add the last digit with total += n % 10.
    4. Drop the last digit with n = n / 10. Without this line n never changes and the loop never ends.
    5. Return total after the loop.

    The solution in Java

    class Solution {
        public int digitSum(int n) {
            int total = 0;
            while (n > 0) {
                total += n % 10;
                n = n / 10;
            }
            return total;
        }
    }
    

    For n = 472, the loop passes look like this:

    Passn at the startDigit addedtotal after
    147222
    24779
    34413

    After the third pass n is 0, the loop ends, and the method returns 13.

    Java details:

    • Integer division. When both operands are int, / gives an int and throws away the fraction, so 47 / 10 is 4, not 4.7.
    • The parameter is a local copy. Changing n inside the method doesn't affect the caller's variable, because Java passes primitives by value.
    • No overflow. The largest input, 1000000000, has a digit sum of 1, and no input can have a sum anywhere near the limit of an int.

    Another way: through text

    A number can also be turned into a string with String.valueOf(n) and the characters added one by one. A digit character is not its number: (int) '7' is 55, so the code subtracts '0', and '7' - '0' is 7. Summing 472 this way gives 13 as well. The remainder-and-divide loop needs no conversion and is the standard way to work with the digits of a number, which later lessons rely on.

    A second trace

    For n = 1005 the loop runs four times. After the passes, total and n are (5, 100), (5, 10), (5, 1) and (6, 0). The two zeros pass through n % 10 without changing total, and the loop goes on because n itself is still greater than 0. The answer is 6.

    Edge cases and common mistakes

    • Zero. The loop doesn't run, and total stays 0.
    • Zeros inside the number. 1005 passes through 5, 0, 0 and 1. Adding a 0 is harmless, and the loop condition looks at n, not at the digits, so it doesn't stop early at a zero digit.
    • Forgetting n = n / 10. This causes an infinite loop.
    • Returning inside the loop. The method would stop after the first digit.

    Testing

    • 472 gives 13.
    • 1005 gives 6.
    • 7 gives 7.
    • 0 gives 0.
    • 1000000000 gives 1.
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free