Start learning free

LESSON 215 OF 289 · WHILE LOOPS - CHALLENGES

Digit Sum in TypeScript: A while Loop 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

    TYPESCRIPT · WHILE LOOPS - CHALLENGES

    Digit Sum in TypeScript, explained

    Problem overview

    The method digitSum receives a non-negative integer 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 5 + 0 + 0 + 1 = 6, and for a single digit like 7 it is 7 itself. The sum for 0 is 0.

    Approach

    A number does not give its digits directly, but two operations take them off one at a time. The remainder n % 10 is the last digit: 472 % 10 is 2. Dividing by 10 and dropping the fraction removes that digit: 472 becomes 47. Repeat until nothing is left, adding each last digit to a running total.

    In TypeScript, / is ordinary division of doubles, so 472 / 10 is 47.2, not 47. Wrapping the result in Math.floor rounds it down to 47. For non-negative numbers, Math.floor and Math.trunc agree.

    Here is what the loop does with 472:

    n at the start of the turnn % 10total after adding
    47222
    4779
    4413

    After the third turn n is 0, the condition n > 0 fails, and the total, 13, is the answer.

    Step by step

    1. Declare total with let as a number, starting at 0. It uses let because it changes inside the loop. If n is 0, the loop never runs and 0 is already right.
    2. Write a while loop that runs as long as n > 0. Each turn removes one digit, so the loop ends when every digit is gone.
    3. Add the last digit: total += n % 10.
    4. Drop the last digit: n = Math.floor(n / 10). Without this line n never changes and the loop never ends.
    5. Return total after the loop.

    The solution in TypeScript

    class Solution {
        digitSum(n: number): number {
            let total: number = 0;
            while (n > 0) {
                total += n % 10;
                n = Math.floor(n / 10);
            }
            return total;
        }
    }
    
    • The parameter is changed. Assigning to n is allowed. The caller's number is not affected, because numbers are passed by value.
    • : number is only a label. TypeScript removes it when compiling to JavaScript. The type does not make n an integer: a number is a double.
    • Large inputs are fine. Doubles hold every integer exactly up to 2^53, far above the limit of 10^9, and there is no integer overflow to worry about. digitSum(1000000000) returns 1.

    Complexity

    Time: O(log n). The loop runs once per digit, and a number n has about log10(n) digits. For the limit of 10^9 that is at most 10 turns.

    Space: O(1). Only total is added.

    Edge cases and common mistakes

    • Zero. The loop is skipped and the function returns 0.
    • Zeros inside the number. 1005 gives 6: each 0 is a turn that adds nothing.
    • Forgetting Math.floor. n / 10 turns 472 into 47.2, then 4.72, and so on. The remainders become fractions such as 4.72 % 10, so the loop runs far longer than the number of digits and the total is wrong.
    • Using const for total. The compiler reports an error on total +=, since a constant cannot be reassigned.
    • Looping while n >= 0. The condition never becomes false, because Math.floor(0 / 10) is 0 again.

    Testing

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