Start learning free

LESSON 215 OF 291 · WHILE LOOPS - CHALLENGES

Digit Sum in Kotlin: 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 6
    Ctrl + Enter to check

    KOTLIN · WHILE LOOPS - CHALLENGES

    Digit Sum in Kotlin, explained

    Problem overview

    The function 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 6, because the zeros add nothing. A one-digit number is its own sum, and 0 gives 0.

    Approach

    A number doesn't hand you its digits, but two operators do. The remainder n % 10 is the last digit (472 % 10 is 2). Integer division n / 10 removes the last digit (472 / 10 is 47). So the plan is a loop: add the last digit to a running total, drop it, and repeat until nothing is left.

    Here is the loop on 472, with the values printed after each pass:

    PassDigit addednum aftertotal after
    12472
    2749
    34013

    After the third pass num is 0, the loop stops, and 13 is the answer.

    Step by step

    1. Copy n into num. Function parameters in Kotlin are read-only, so the loop can't change n. A var variable can be reassigned, so the loop takes digits off num instead.
    2. Start total at 0. Nothing has been added yet. For n = 0 the loop never runs, and 0 is the right answer.
    3. Loop while num > 0. Each pass removes one digit, so num reaches 0 when all digits are gone.
    4. Add the last digit. total += num % 10.
    5. Drop the last digit. Store num / 10 back in num. Without this line the loop never ends.
    6. Return total after the loop.

    The solution in Kotlin

    class Solution {
        fun digitSum(n: Int): Int {
            var num = n
            var total = 0
            while (num > 0) {
                total += num % 10
                num = num / 10
            }
            return total
        }
    }
    

    Some details worth knowing:

    • / on two Int values drops the remainder. 47 / 10 is 4, not 4.7. That is what makes it remove a digit.
    • var versus val. Assigning to a val, or to the parameter n, is a compile error: 'val' cannot be reassigned.
    • Int is enough. The largest input, 1000000000, fits in an Int, and its digit sum is 1.

    Why a while loop

    A for loop is for a known number of repetitions, such as the characters of a string. Here the number of passes depends on how many digits n has, and the code doesn't know that count beforehand. A while loop repeats until a condition fails, which is the natural fit: keep going while there are digits left. The condition num > 0 is also what makes the empty case, n = 0, work without any special handling.

    The same pair of operations, % 10 and / 10, is the standard way to take a number apart in any base-10 exercise. Counting digits, reversing a number and checking palindromes are all variations on this loop.

    Complexity

    Time is O(d), where d is the number of digits, because each pass removes one. Space is O(1): two variables.

    Edge cases and common mistakes

    • Zero. num > 0 is false at once, so the function returns 0.
    • Forgetting num = num / 10. num never changes and the loop runs forever.
    • Using val for total. The code won't compile, since total changes in the loop.
    • Zeros inside the number. 1005 passes through 5, 0, 0, 1; the zeros add 0 and the loop still removes them.

    Testing

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