Start learning free

LESSON 212 OF 671 · WHILE LOOPS - CHALLENGES

Digit Sum in JavaScript: Peeling Digits with % and Math.floor

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

    JAVASCRIPT · WHILE LOOPS - CHALLENGES

    Digit Sum in JavaScript, explained

    Problem overview

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

    Approach: take the last digit, then drop it

    A number written in base 10 gives up its digits to two simple operations:

    • n % 10 is the remainder after dividing by 10, which is the last digit. 472 % 10 is 2.
    • Dividing by 10 and throwing away the fraction removes the last digit. 472 / 10 is 47.2, and rounding down gives 47.

    Repeat both operations until nothing is left. Each time round the loop adds one digit to a running total and shortens the number by one digit. When n reaches 0, every digit has been added. The digits come off from the right, but a sum doesn't care about order.

    Step by step

    1. Declare total with let, starting at 0. It changes inside the loop, so const would fail. Starting at 0 also gives the right answer for n = 0, where the loop never runs.
    2. Loop while n > 0. Each pass removes one digit, so the condition becomes false once all digits are gone.
    3. Add n % 10 to total with +=.
    4. Replace n with Math.floor(n / 10). JavaScript has only one kind of number, so / keeps the fraction: 472 / 10 is 47.2. Math.floor rounds it down to 47. Without this line, n never changes and the loop never ends.
    5. Return total after the loop.

    The solution in JavaScript

    class Solution {
        digitSum(n) {
            let total = 0;
            while (n > 0) {
                total += n % 10;
                n = Math.floor(n / 10);
            }
            return total;
        }
    }
    

    Here is digitSum(472) pass by pass, with the values after each pass:

    Passntotal
    1472
    249
    3013

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

    • Parameters can be reassigned. The method changes n directly. That is fine, because numbers are passed by value and the caller's variable is unaffected.
    • Why Math.floor and not a cast. JavaScript has no integer division operator. Math.floor(n / 10) is the usual way to get one for non-negative numbers. For negative numbers Math.floor rounds toward negative infinity, but this lesson only has non-negative input.

    How many passes

    Time: O(d), where d is the number of digits of n, which is about log10(n). The loop runs once per digit. For the largest input, 10^9, that is 10 passes. Space: O(1). Only two variables are used.

    Edge cases and common mistakes

    • Zero. digitSum(0) returns 0 because the loop never runs.
    • Zeros inside the number. digitSum(1005) adds 5, 0, 0 and 1, and returns 6.
    • The largest input. digitSum(1000000000) returns 1. All numbers up to 10^9 are far below the point where JavaScript starts losing integer precision (2^53), so the arithmetic is exact.
    • Forgetting Math.floor. n / 10 alone leaves fractions behind, so n shrinks as 47.2, 4.72, 0.472 and so on, and never becomes exactly 0 in a useful way. The sum is then wrong or the loop runs for a very long time.
    • Using const for total. Assigning to a const variable throws a TypeError at the first +=.

    Testing

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