Start learning free

LESSON 215 OF 291 · WHILE LOOPS - CHALLENGES

Digit Sum in Scala: % 10 and / 10 in a while Loop

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

    SCALA · WHILE LOOPS - CHALLENGES

    Digit Sum in Scala, explained

    Problem overview

    The function digitSum takes a non-negative Int, n, and returns the sum of its digits. For n = 472 the digits are 4, 7 and 2, and the sum is 13. For n = 1005 the answer is 6, because the zeros add nothing, and for n = 7 it is 7. When n is 0 the sum is 0.

    Approach

    You can't index into a number the way you index into a string, so the digits have to be taken off arithmetically. Two operations do it:

    • num % 10 is the remainder after dividing by 10, which is the last digit: 472 % 10 is 2.
    • num / 10 on two Int values drops the remainder, which removes the last digit: 472 / 10 is 47.

    Repeat both until nothing is left. Each turn of a loop adds one digit to a running total and then removes it from the number.

    Step by step

    1. Copy n into var num. Function parameters in Scala are immutable, so the loop can't change n, but it can change a var.
    2. Create var total, starting at 0. If n is 0, the loop never runs and 0 is already the right answer.
    3. Write a while loop that runs as long as num > 0. A number with no digits left is 0, which ends the loop.
    4. Inside the loop, add num % 10 to total with +=.
    5. Still inside, replace num with num / 10. Without this line num never changes and the loop never ends.
    6. After the loop, return total.

    Here is the state after each turn for n = 472:

    Turnnum after the turntotal after the turn
    1472
    249
    3013

    Why the loop must end

    Each turn divides num by 10 with the remainder dropped, so it gets smaller every time, and a non-negative Int that keeps shrinking reaches 0. A number with d digits needs exactly d turns, because every division removes exactly one digit. The loop therefore runs once per digit, and the work grows only with the length of the number, not its size: even 1000000000 takes ten turns. The order of the two lines inside the loop matters too: read the digit with % 10 first, then drop it with / 10. Swapping them would add the wrong digit.

    The solution in Scala

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

    Details that matter in Scala:

    • var declares a variable you can reassign, val one you can't. Both num and total change, so both are var.
    • total += num % 10 is shorthand for total = total + num % 10. The % operator binds tighter than +, so the remainder is computed first.
    • / between two Int values is integer division and truncates. With a Double on either side it would keep a fraction and the loop would behave differently.
    • Int is 32 bits and holds up to 2147483647. The lesson's largest input, 1000000000, fits comfortably.

    Edge cases and common mistakes

    • Zero. digitSum(0) returns 0, because 0 > 0 is false and the loop is skipped.
    • Zeros inside the number. For 1005 the digits taken are 5, 0, 0, 1: the sum is 6.
    • Forgetting to shrink num. If the division line is missing, the same last digit is added forever.
    • Looping on num >= 0. This never stops, because 0 / 10 is 0 again.

    Testing

    digitSum(472)  -> 13
    digitSum(1005) -> 6
    digitSum(7)    -> 7
    digitSum(0)    -> 0
    
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free