Start learning free

LESSON 51 OF 414 · CALCULATIONS - CHALLENGES

Buy Candy in Scala: Integer Division and Arithmetic

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

    SCALA · CALCULATIONS - CHALLENGES

    Buy Candy in Scala, 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.

    In the example, price = 4 and balance = 9. Nine dollars buy two boxes, which cost 8. A third box would bring the total to 12, so you need 3 more dollars. The answer is 3.

    Approach

    The question has three parts, and each is one short calculation:

    1. How many whole boxes does the balance cover?
    2. What would one more box than that cost in total?
    3. How far is that total from the money you have?

    The first part is integer division. Dividing two Int values in Scala gives an Int and drops the fractional part, so 9 / 4 is 2, exactly the number of whole boxes. The remaining parts are a multiplication and a subtraction.

    One consequence deserves attention. If the balance is an exact multiple of the price, you can already buy balance / price boxes with nothing left over. One more box still costs a full price, so the answer is price, never 0. With price = 4 and balance = 8, the answer is 4.

    Step by step

    1. Count the whole boxes. Declare a val named boxes with balance / price. A val is an immutable value: once set, it can't be reassigned, which is right for a result you only read afterwards.
    2. Price one more box than that. Declare balanceNeeded as (boxes + 1) * price. The parentheses make the addition happen before the multiplication; without them, boxes + 1 * price would multiply first.
    3. Find the gap. Declare extraBalance as balanceNeeded - balance. This is the money still missing.
    4. Return it as the result of the method.

    The solution in Scala

    class Solution {
        def buyCandy(price: Int, balance: Int): Int = {
            val boxes = balance / price
            val balanceNeeded = (boxes + 1) * price
            val extraBalance = balanceNeeded - balance
            return extraBalance
        }
    }
    

    Scala details:

    • Inferred types. None of the three val lines names a type. Scala infers Int from the right-hand side. You could write val boxes: Int = balance / price and nothing would change.
    • Integer division truncates. Both operands are Int, so the result is cut toward zero. For the non-negative values in this problem that is the same as rounding down.
    • return is optional. The last expression of the block is its value, so ending the method with extraBalance alone is equivalent.

    Complexity

    Time: O(1). The method performs a fixed number of arithmetic operations whatever the input values are.

    Space: O(1). It stores three integers.

    Edge cases and common mistakes

    • Exact multiples. buyCandy(4, 8) is 4, not 0. Computing boxes * price - balance instead would give 0 here and a negative number everywhere else.
    • Not enough for one box. buyCandy(5, 3) is 2: boxes is 0, and one box costs 5, which is 2 more than you have. A balance of 0 works too: buyCandy(4, 0) is 4.
    • Forgetting the parentheses. boxes + 1 * price computes boxes + price, which is wrong unless price is 1.
    • Division by zero. A price of 0 makes balance / price throw an ArithmeticException for Int values. The problem implies a positive price.
    • Using a decimal division. Converting to Double would keep the fraction (2.25 boxes) and break the count of whole boxes.

    Testing

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