Start learning free

LESSON 216 OF 292 · WHILE LOOPS - CHALLENGES

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

    SWIFT · WHILE LOOPS - CHALLENGES

    Digit Sum in Swift, explained

    Problem overview

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

    Approach

    You can't index into an Int to get its digits, but two arithmetic operations give you the same thing.

    • num % 10 is the remainder of 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. Here are the values for 472, taken from a run of the solution:

    numnum % 10total after adding
    47222
    4779
    4413

    After the third turn, num is 0 and the loop stops. The total, 13, is the answer.

    The same two operations work for any task that looks at a number digit by digit: counting digits, reversing a number or finding the largest digit. In each case the loop reads the last digit with % 10 and removes it with / 10.

    Step by step

    1. Copy n into var num. Function parameters are constants in Swift, so the loop can't change n. A var can be reassigned, and a let can't.
    2. Create var total = 0. Nothing has been added yet. If n is 0, the loop never runs and 0 is already the right answer.
    3. Loop while num > 0. Each turn removes one digit, so num reaches 0 once all of them are gone.
    4. Add num % 10 to total with +=.
    5. Replace num with num / 10. Without this line, num never changes and the loop never ends.
    6. Return total after the loop.

    The solution in Swift

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

    Swift details worth knowing:

    • Integer division truncates. Dividing two Int values gives an Int, and the fractional part is dropped: 7 / 2 is 3. For the non-negative numbers here, truncating and rounding down are the same thing.
    • No parentheses around the condition. Swift's while takes the condition without them, but the braces are required.
    • Shorter form. num /= 10 means the same as num = num / 10.
    • No overflow worries. Int is 64 bits, so values up to a billion fit easily, and the digit total is at most 81 for numbers below a billion.

    Edge cases and common mistakes

    • Zero. digitSum(0) skips the loop and returns 0.
    • Zeros inside a number. For 1005, the loop adds 5, 0, 0 and 1, and the total is 6.
    • Forgetting num = num / 10. The loop repeats forever with the same last digit.
    • Returning inside the loop. The function would stop after the first digit.
    • Using let for total. A constant can't be changed by +=, so the code doesn't compile.

    Testing

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