Return Exact Cash Register Change
Learn this problemProblem statement
Given the purchase price purchasePrice and the amount of cash paid cashPaid as exact decimal strings, report the cash-register result.
If the cash paid is less than the purchase price, return ERROR. If the amounts are equal, return ZERO. Otherwise, make the exact change using the fewest denominations from the following values: PENNY (0.01), NICKEL (0.05), DIME (0.10), QUARTER (0.25), HALF DOLLAR (0.50), ONE (1.00), TWO (2.00), FIVE (5.00), TEN (10.00), TWENTY (20.00), FIFTY (50.00), and ONE HUNDRED (100.00).
Sort all used denomination names alphabetically and join them with commas. Repeat a name when that denomination is used more than once.
Function
cashRegister(purchasePrice: String, cashPaid: String) → StringExamples
Example 1
purchasePrice = "12.37"cashPaid = "20.00"return = "DIME,FIVE,HALF DOLLAR,PENNY,PENNY,PENNY,TWO"The change is 7.63. A minimum-denomination decomposition uses FIVE, TWO, HALF DOLLAR, DIME, and three PENNY values; the returned names are sorted alphabetically.
Example 2
purchasePrice = "35.00"cashPaid = "35.00"return = "ZERO"No change is due because the two amounts are equal.
Example 3
purchasePrice = "10.00"cashPaid = "5.00"return = "ERROR"The cash paid is less than the purchase price.
Constraints
- Each input is a valid nonnegative decimal string with one or two fractional digits.
0.00 <= purchasePrice, cashPaid <= 1000000.00- The inputs contain no currency symbols, grouping separators, signs, or surrounding whitespace.