We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Account Balance After Rounded Purchase

Number: 2955

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

You start with a bank account balance of 100 dollars. Given a purchase amount, you first round it to the nearest multiple of 10 (with 5 rounding upward), then subtract this rounded amount from your balance. The task is to return the final balance.


Key Insights

  • The purchase amount is rounded to the nearest multiple of 10.
  • Adding 5 to the purchase amount before integer division by 10 effectively rounds the value correctly.
  • The final balance is 100 minus the rounded purchase amount.
  • A simple mathematical computation is used with constant time complexity.

Space and Time Complexity

Time Complexity: O(1)
Space Complexity: O(1)


Solution

The solution uses basic arithmetic operations. To round the purchase amount to the nearest multiple of 10, we add 5 and then perform integer division by 10 before multiplying by 10. This handles the rounding upward in cases where the units digit is 5 or more. Subtracting this rounded amount from the initial balance (100) yields the final balance.


Code Solutions

# Python solution with line-by-line comments

def accountBalanceAfterPurchase(purchaseAmount):
    # Calculate the rounded purchase amount
    # Adding 5 and integer dividing by 10, then multiplying by 10 rounds the purchaseAmount
    roundedAmount = ((purchaseAmount + 5) // 10) * 10
    # Subtract the rounded amount from 100 to get final balance
    return 100 - roundedAmount

# Example usage:
print(accountBalanceAfterPurchase(15))  # Expected output: 80
← Back to All Questions