Start learning free

LESSON 51 OF 415 · CALCULATIONS - CHALLENGES

Buy Candy in Swift: Integer Division and Remainders

Practice Read the full explanation

A box of candy costs price dollars. You have balance dollars. Compute the number of boxes of candy you can buy and return how many more dollars you need to buy one more box of candy.

Example:

Input: price = 4, balance = 9

Output: 3

Explanation:
You can buy two boxes of candy that costs 4 * 2 = 8 dollars.
If you would have 12 dollars you could buy 3 boxes (one more), so you would need 3 more dollars.
Hints:

The number of boxes we can buy is the integer part of the division of balance by price. Let's store this number in a variable boxes.

We want to buy one more box, so a total of boxes + 1 boxes, which require (boxes + 1) * price dollars. Let's store this product into another variable balanceNeeded.

Finally the answer is the difference between balanceNeeded and balance.
STEP 1 OF 4
    Ctrl + Enter to check

    SWIFT · CALCULATIONS - CHALLENGES

    Buy Candy in Swift, explained

    Problem overview

    A box of candy costs price dollars and you have balance dollars. The method buyCandy returns how many more dollars you need to afford one more box than you can buy now.

    With price = 4 and balance = 9, you can buy two boxes, which cost 8 dollars. Three boxes cost 12 dollars, and you have 9, so you need 3 more. The answer is 3.

    Approach

    The answer comes from three small facts:

    1. The number of boxes you can already buy is the whole-number part of balance / price.
    2. One more box means boxes + 1 boxes in total, and their price is (boxes + 1) * price.
    3. The money you are missing is that price minus balance.

    An alternative is a loop that adds one box at a time until the total passes the balance. Arithmetic gets the result directly, with no loop.

    Step by step

    1. Count the whole boxes. Declare boxes as balance / price. Both are Int, so Swift divides without keeping a fraction: 9 / 4 is 2.
    2. Price the next count. Declare balanceNeeded as (boxes + 1) * price. The parentheses make the + 1 happen before the multiplication. Without them, boxes + 1 * price multiplies first and gives a different number.
    3. Find the gap. Declare extraBalance as balanceNeeded - balance. Because the next box is always more than you have, the gap is positive.
    4. Return the gap. The method promises an Int, so return extraBalance finishes the job.

    The solution in Swift

    class Solution {
        func buyCandy(_ price: Int, _ balance: Int) -> Int {
            let boxes = balance / price
            let balanceNeeded = (boxes + 1) * price
            let extraBalance = balanceNeeded - balance
            return extraBalance
        }
    }
    

    Swift details worth knowing:

    • Integer division truncates. Dividing two Int values gives an Int and drops the fraction, rounding toward zero. For non-negative numbers like these, that is the same as rounding down.
    • let for values that never change. Each intermediate result is computed once, so let fits. Swift would flag a var that is never modified.
    • Type inference. The constants have no written types. Swift infers Int from the parameters.
    • Division by zero crashes. A price of 0 would stop the program at balance / price, so the lesson assumes a positive price.

    Why the answer is never zero

    When balance is an exact multiple of price, such as 8 and 4, you can buy exactly 2 boxes with nothing left over. Another box still costs a full 4 dollars, so the answer is 4. The formula handles this on its own: boxes is 2, balanceNeeded is 12, and 12 - 8 is 4.

    A shortcut written as price - balance % price gives the same result. It is shorter, but the three named steps show the reasoning.

    To check the formula by hand, take price = 5 and balance = 23: boxes is 4, balanceNeeded is 25, and the gap is 2.

    Edge cases and common mistakes

    • Balance below the price. With price = 5 and balance = 3, boxes is 0 and the answer is 2.
    • Zero balance. With price = 4 and balance = 0, the answer is 4, a full price.
    • Missing parentheses. boxes + 1 * price is not the cost of boxes + 1 boxes.
    • Returning balanceNeeded. That is the total cost, not the missing amount.
    • Swapped parameters. The order is price first, then balance.

    Testing

    • price = 4, balance = 9 gives 3.
    • price = 4, balance = 8 gives 4.
    • price = 4, balance = 0 gives 4.
    • price = 5, balance = 3 gives 2.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free