Start learning free

LESSON 211 OF 667 · WHILE LOOPS - CHALLENGES

Digit Sum in C++: 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

    C++ · WHILE LOOPS - CHALLENGES

    Digit Sum in C++, explained

    Problem overview

    The function digitSum receives a non-negative integer n, up to 1,000,000,000, and returns the sum of its digits. The number 472 has the digits 4, 7 and 2, so the answer is 13. The number 1005 gives 5 + 0 + 0 + 1 = 6, because zeros add nothing, and a one-digit number such as 7 is its own digit sum. For n = 0 the sum is 0.

    Approach

    The number is stored as a value, not as a list of digits, so the function takes the digits off one at a time using two integer operations:

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

    Repeating "add the last digit, then drop it" until nothing is left visits every digit exactly once, from the right. When the number has become 0, there are no digits left, so the loop condition is n > 0.

    Here is the loop on n = 472, showing the state after each pass:

    n=47 total=2
    n=4 total=9
    n=0 total=13
    

    Step by step

    1. Create total as an int starting at 0. Nothing has been added yet. If n is 0, the loop never runs and 0 is already the right answer.
    2. Start a while loop that runs while n > 0. Each pass removes one digit, so n reaches 0 once every digit is gone.
    3. Add n % 10 to total. This is the last digit of the current n.
    4. Replace n with n / 10. Without this line n never changes and the loop never ends.
    5. Return total after the loop.

    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;
        }
    };
    

    Some C++ details:

    • Integer division. When both operands are int, / gives an int and the fractional part is discarded. That is exactly the "drop the last digit" behaviour. Dividing by 10.0 instead would give a fractional result.
    • n is a copy. The parameter is passed by value, so the loop changes only the function's own variable, and the caller's number stays the same.
    • The range fits in int. The largest allowed input, 1,000,000,000, is below the 32-bit limit of 2,147,483,647, and the digit sum is tiny compared with it: 999999999 gives 81.

    Edge cases and common mistakes

    • Zero. The condition n > 0 is false at the start, so the function returns 0.
    • Trailing zeros. For 1005 the loop adds 5, 0, 0 and 1. The zeros pass through harmlessly.
    • The largest input. For 1000000000 the answer is 1, after nine passes that add 0 and a last pass that adds 1.
    • Forgetting n = n / 10. The loop then repeats forever with the same last digit.
    • Using n >= 0. Since 0 / 10 is 0, n never becomes negative and the loop would never stop.

    Testing

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