Account Balance After Rounded Purchase

You initially have 100 dollars in your account. You want to make a purchase, and the purchase amount will be rounded to the nearest multiple of 10. If there’s more than one nearest multiple of 10, the larger one is chosen. You need to return the account balance after making the purchase.

Approach:

  1. Determine the rounded amount by finding the nearest multiple of 10 to the given purchaseAmount.
  2. If the purchaseAmount is exactly midway between two multiples of 10, choose the larger one.
  3. Subtract the rounded amount from the initial balance of 100 dollars.
  4. Return the resulting balance.

Calculating the Rounded Amount:

  • If purchaseAmount modulo 10 is less than 5, subtract it from the purchaseAmount to round down.
  • Otherwise, add the difference between 10 and purchaseAmount modulo 10 to round up.

Now, let’s put this into code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
    def accountBalanceAfterPurchase(self, purchaseAmount: int) -> int:
        # Find the remainder of dividing purchaseAmount by 10
        remainder = purchaseAmount % 10

        # If remainder is 5 or more, round up to the next multiple of 10
        if remainder >= 5:
            roundedAmount = purchaseAmount + (10 - remainder)
        else:
            roundedAmount = purchaseAmount - remainder

        # Return the final balance by subtracting the rounded amount from 100
        return 100 - roundedAmount

Key Takeaways:

  • The problem involves a basic understanding of rounding to the nearest multiple.
  • The solution uses the modulo operation to find the remainder and then performs rounding accordingly.
  • The code is clear and concise, addressing the requirements of the problem within the given constraints.