Problem
Initially, you have a bank account balance of 100 dollars.
You are given an integer purchaseAmount
representing the amount you will spend on a purchase in dollars, in other words, its price.
When making the purchase, first the purchaseAmount
is rounded to the nearest multiple of 10. Let us call this value roundedAmount
. Then, roundedAmount
dollars are removed from your bank account.
Return an integer denoting your final bank account balance after this purchase.
Notes:
- 0 is considered to be a multiple of 10 in this problem.
- When rounding, 5 is rounded upward (5 is rounded to 10, 15 is rounded to 20, 25 to 30, and so on).
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
0 <= purchaseAmount <= 100
Solution
Method 1 – Rounding to Nearest Multiple of 10
Intuition
The key idea is to round the purchase amount to the nearest multiple of 10, subtract it from the initial balance (100), and return the result. Rounding is done such that values ending in 5 or more round up (e.g., 15 → 20), and less than 5 round down (e.g., 13 → 10).
Approach
- Start with a balance of 100.
- To round
purchaseAmount
to the nearest multiple of 10:
- Add 5 to
purchaseAmount
and perform integer division by 10, then multiply by 10. - This ensures numbers ending in 5 or more round up.
- Subtract the rounded amount from the balance.
- Return the result.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
— Only basic arithmetic operations. - 🧺 Space complexity:
O(1)
— No extra space used.