[Programmers / JAVA] Level 1 Calculating the Shortfall (82612)
[Programmers / JAVA] Level 1 Calculating the Shortfall (82612)
| Rank | Language Used |
|---|---|
| Level 1 | 🖼️ JAVA |
The newly opened ride is so popular that the line never ends. This ride originally cost price won, but it was decided that the Nth time you ride it, you'll be charged N times the original price. That is, if the initial fare was 100, the 2nd ride costs 200, and the 3rd ride costs 300, with the fare increasing each time. Complete the solution function to return how much money is missing from the amount you currently have if you ride the attraction count times. However, if the amount is not insufficient, return 0.
- Ride fare price: 1 ≤ price ≤ 2,500, price is a natural number
- Initial amount of money money: 1 ≤ money ≤ 1,000,000,000, money is a natural number
- Number of rides count: 1 ≤ count ≤ 2,500, count is a natural number
| price | money | count | result |
|---|---|---|---|
| 3 | 20 | 4 | 10 |
Example #1
If a customer wants to ride an attraction costing 3 four times, and currently has 20, the total fare needed is 30 (= 3+6+9+12), which is short by 10, so return 10.
This ride goes against the grain of the times — the more you ride, the more you're charged...
Run a for loop count times, accumulating price * count, and return the result.
Note that the return value should be long. Sometimes people carelessly declare the variable as int and return it; converting from int to the wider-range long happens automatically without issue, so returning an int won't cause a compile error. However, during the grading process, if the value exceeds the range of int, it can't be represented properly, resulting in a wrong answer.
JAVA
/** * Calculating the Shortfall class * * @author RWB * @since 2021.12.12 Sun 16:43:20 */ class Solution { /** * Method that returns the answer * * @param price: [int] ride fare * @param money: [int] money on hand * @param count: [int] number of times the ride was used * * @return [long] answer */ public long solution(int price, int money, int count) { long total = 0; while (count > 0) { total += (long) price * count; count--; } return Math.max(total - money, 0); } }
Be careful not to return total as an int.
