# Account Balance After Rounded Purchase
**Difficulty:** EASY
[External](https://leetcode.com/problems/account-balance-after-rounded-purchase)
Canonical: https://scaleengineer.com/dsa/problems/account-balance-after-rounded-purchase
**Patterns:** [Math](https://scaleengineer.com/dsa/patterns/math)
---
## 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).

**Example 1:**

**Input:** purchaseAmount = 9

**Output:** 90

**Explanation:**

The nearest multiple of 10 to 9 is 10\. So your account balance becomes 100 - 10 = 90.

**Example 2:**

**Input:** purchaseAmount = 15

**Output:** 80

**Explanation:**

The nearest multiple of 10 to 15 is 20\. So your account balance becomes 100 - 20 = 80.

**Example 3:**

**Input:** purchaseAmount = 10

**Output:** 90

**Explanation:**

10 is a multiple of 10 itself. So your account balance becomes 100 - 10 = 90.

**Constraints:**

* `0 <= purchaseAmount <= 100`

# Approaches
## Using Floating-Point Arithmetic and Math.round
This approach involves converting the `purchaseAmount` to a floating-point number to leverage the built-in `Math.round()` function. The amount is first divided by 10.0, then rounded to the nearest whole number using `Math.round()`, and finally multiplied back by 10 to get the nearest multiple of 10.
**Time:** O(1) - The number of operations (casting, division, rounding, multiplication, subtraction) is constant and does not depend on the size of `purchaseAmount`. · **Space:** O(1) - Only a few variables are used for intermediate calculations, so the space used is constant.
**Pros:** Leverages a well-known standard library function, making the rounding intention clear to developers familiar with it.
**Cons:** Introduces floating-point arithmetic, which is generally less efficient than pure integer arithmetic.; Can be prone to precision issues in more complex scenarios, although it's safe for the given constraints.; Slightly more verbose due to the need for type casting.
### Explanation
The core idea is to use the standard library's rounding function. `Math.round(x)` in Java rounds a float or double to the nearest long. For values ending in .5, it rounds up, which perfectly matches the problem's requirement. The algorithm is as follows:
1.  Cast `purchaseAmount` to a `double`.
2.  Divide the result by `10.0`.
3.  Apply `Math.round()` to this value.
4.  Multiply the rounded value by `10` to get `roundedAmount`.
5.  Subtract `roundedAmount` from `100` to get the final balance.

```java
class Solution {
    public int accountBalanceAfterPurchase(int purchaseAmount) {
        double amountAsDouble = (double) purchaseAmount / 10.0;
        int roundedAmount = (int) Math.round(amountAsDouble) * 10;
        return 100 - roundedAmount;
    }
}
```
### Algorithm
- Convert `purchaseAmount` to a floating-point type (e.g., `double`).
- Divide the value by `10.0`.
- Use the `Math.round()` function to round the result to the nearest integer. This function correctly handles rounding up from .5, which matches the problem's requirement.
- Multiply the rounded integer by `10` to get the `roundedAmount`.
- Calculate the final balance by subtracting `roundedAmount` from `100`.
- Return the final balance.

## Conditional Logic based on the Last Digit
This approach directly implements the rounding rule described in the problem by examining the last digit of the `purchaseAmount`. An `if-else` statement is used to decide whether to round the amount up or down based on its last digit.
**Time:** O(1) - The solution involves a fixed number of arithmetic operations and one conditional check, making it constant time. · **Space:** O(1) - A constant amount of extra space is used for variables like `remainder` and `roundedAmount`.
**Pros:** The logic is very explicit and easy to follow, as it directly translates the problem's rules into code.; Uses only integer arithmetic, which is efficient and avoids potential floating-point precision issues.
**Cons:** Slightly more verbose than a purely mathematical approach due to the conditional block.
### Explanation
The rounding decision depends on whether the last digit is 5 or more. We can get the last digit using the modulo operator (`% 10`).
- If the last digit is less than 5, we round down. The `roundedAmount` is the `purchaseAmount` with its last digit effectively set to zero. This can be calculated as `(purchaseAmount / 10) * 10`.
- If the last digit is 5 or greater, we round up to the next multiple of 10. This can be calculated as `(purchaseAmount / 10 + 1) * 10`.

This logic explicitly separates the two cases, making it very easy to read and understand.

```java
class Solution {
    public int accountBalanceAfterPurchase(int purchaseAmount) {
        int remainder = purchaseAmount % 10;
        int roundedAmount;
        if (remainder < 5) {
            roundedAmount = (purchaseAmount / 10) * 10;
        } else {
            roundedAmount = (purchaseAmount / 10 + 1) * 10;
        }
        return 100 - roundedAmount;
    }
}
```
### Algorithm
- Find the last digit of `purchaseAmount` using the modulo operator (`purchaseAmount % 10`).
- Use an `if-else` condition to check if the last digit is less than 5.
- If it is, round down by finding the multiple of 10 just below or equal to `purchaseAmount`. This is calculated as `(purchaseAmount / 10) * 10`.
- If the last digit is 5 or greater, round up by finding the multiple of 10 just above `purchaseAmount`. This is calculated as `(purchaseAmount / 10 + 1) * 10`.
- Calculate the final balance by subtracting the `roundedAmount` from `100`.
- Return the final balance.

## Efficient Integer Arithmetic
This is the most concise and efficient approach. It uses a clever mathematical trick with integer division to perform the required rounding in a single expression, avoiding explicit conditional statements or floating-point math.
**Time:** O(1) - This is the most performant approach in terms of raw operations, involving only a few simple integer arithmetic calculations. · **Space:** O(1) - No extra space is needed beyond a variable for the result, making it maximally space-efficient.
**Pros:** Extremely concise and elegant.; Highly efficient as it uses only simple integer operations and avoids branching (if-statements).
**Cons:** The mathematical trick might be less intuitive to someone unfamiliar with it compared to an explicit `if-else` statement.
### Explanation
The standard method for rounding an integer `x` to the nearest multiple of `n` (where `n/2` rounds up) is to calculate `((x + n/2) / n) * n`. In our case, `n` is 10, so we add 5.

The formula `((purchaseAmount + 5) / 10) * 10` correctly calculates the `roundedAmount`.
- **Why it works (e.g., `purchaseAmount = 12`):** `(12 + 5) / 10 = 17 / 10 = 1` (integer division). Then `1 * 10 = 10` (rounded down).
- **Why it works (e.g., `purchaseAmount = 15`):** `(15 + 5) / 10 = 20 / 10 = 2`. Then `2 * 10 = 20` (rounded up).

This single line of calculation elegantly handles both rounding cases. The final balance is then `100 - roundedAmount`.

```java
class Solution {
    public int accountBalanceAfterPurchase(int purchaseAmount) {
        int roundedAmount = ((purchaseAmount + 5) / 10) * 10;
        return 100 - roundedAmount;
    }
}
```
### Algorithm
- Add 5 to the `purchaseAmount`.
- Perform integer division of the result by 10. This step effectively gets the tens digit, rounded up if the original last digit was 5 or more.
- Multiply the result by 10 to scale it back, resulting in the `roundedAmount`.
- Calculate the final balance by subtracting `roundedAmount` from `100`.
- Return the final balance.

# Solutions
### Java

```java
class Solution {
public
  int accountBalanceAfterPurchase(int purchaseAmount) {
    int diff = 100, x = 0;
    for (int y = 100; y >= 0; y -= 10) {
      int t = Math.abs(y - purchaseAmount);
      if (t < diff) {
        diff = t;
        x = y;
      }
    }
    return 100 - x;
  }
}

```

### CPP

```cpp
class Solution {
public:
  int accountBalanceAfterPurchase(int purchaseAmount) {
    int diff = 100, x = 0;
    for (int y = 100; y >= 0; y -= 10) {
      int t = abs(y - purchaseAmount);
      if (t < diff) {
        diff = t;
        x = y;
      }
    }
    return 100 - x;
  }
};

```

### Python

```python
class Solution:
    def accountBalanceAfterPurchase(self, purchaseAmount: int) -> int: diff, x = 100, 0 for y in range(100, - 1, - 10): if (t: = abs(y - purchaseAmount)) < diff: diff = t x = y return 100 - x

```
