Start learning free

LESSON 214 OF 289 · WHILE LOOPS - CHALLENGES

Digit Sum in C#: Peeling Digits 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

    C# · WHILE LOOPS - CHALLENGES

    Digit Sum in C#, explained

    Problem overview

    DigitSum receives a non-negative int n and returns the sum of its digits. For 472 the digits are 4, 7 and 2, so the answer is 13. For 1005 it is 6, since the zeros add nothing. A one-digit number is its own sum, and 0 gives 0.

    Approach

    There is no need to turn the number into text. Two integer operations take it apart:

    • n % 10 is the remainder of 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. Integer division in C# truncates, so there is no fractional part.

    Repeat: add the last digit to a running total, then remove it. When the number reaches 0, every digit has been used.

    Step by step

    1. Create total as an int set to 0. It holds the sum so far. If n is 0, the loop below never runs and 0 is the correct answer.
    2. Write while (n > 0). Each pass handles one digit, and the loop ends when none are left.
    3. Add n % 10 to total with +=.
    4. Divide n by 10 and store the result back in n. Without this line n never changes and the loop never ends.
    5. Return total after the loop.

    For n = 472, the passes look like this:

    PassLast digittotal after addingn after dividing
    12247
    2794
    34130

    Then n is 0, the loop stops, and the method returns 13.

    The solution in C#

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

    The parameter n is a copy of the caller's number, so changing it inside the method doesn't affect the caller. The order of the two lines in the loop matters: read the last digit first, then drop it.

    What the loop keeps true

    Two facts hold at the start of every pass. First, total is the sum of the digits already removed. Second, n holds the digits not yet removed. At the start both are as expected: nothing is removed, total is 0 and n is the whole number. Each pass moves one digit from n into total, so both facts stay true. When n is 0, no digits are left, and total is the sum of all of them. Thinking this way is a good habit for any loop that builds up an answer.

    A while loop is the right tool because the number of digits isn't known when the method starts. A for loop with a fixed count would need that number first.

    Edge cases and common mistakes

    • Zero. The loop is skipped and total stays 0.
    • Zeros inside the number. 1005 goes 5, 0, 0, 1: the zeros add 0 and the loop still removes them. The result is 6.
    • Largest input. A number up to 1,000,000,000 has at most 10 digits, and the digit sum is far below the int limit, so nothing overflows. For 1000000000 the answer is 1.
    • Swapped lines. If you divide before adding, you add the wrong digit and skip the first one.
    • Using / expecting decimals. With two int values, / never gives a fraction. That is what makes this work here.

    Testing

    The solution returns 13 for 472, 6 for 1005, 7 for 7 and 0 for 0.

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free