#2288

Apply Discount to Prices

expert · 1145 · lc medium +32 · verified · 33.8% accepted · 223 likes · top 11%

Description

A sentence is a string of single-space-separated words, each of which may contain digits, lowercase letters, and the dollar sign '$'. A word is a price when it starts with '$' and the rest consists entirely of digits.

- For instance, "$100", "$23", and "$6" are valid prices, while "100", "$", and "$1e5" are not.

Given a string sentence and an integer discount, reduce every price by discount% and express the result with exactly two decimal places.

Return the updated sentence.

Note: all prices have at most 10 digits.

Example 1:

Input: sentence = "there are $1 $2 and 5$ candies in the shop", discount = 50
Output: "there are $0.50 $1.00 and 5$ candies in the shop"
Explanation:
The words which represent prices are "$1" and "$2".
- A 50% discount on "$1" yields "$0.50", so "$1" is replaced by "$0.50".
- A 50% discount on "$2" yields "$1". Since we need to have exactly 2 decimal places after a price, we replace "$2" with "$1.00".

Example 2:

Input: sentence = "1 2 $3 4 $5 $6 7 8$ $9 $10$", discount = 100
Output: "1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$"
Explanation:
Applying a 100% discount on any price will result in 0.
The words representing prices are "$3", "$5", "$6", and "$9".
Each of them is replaced by "$0.00".

Code

1
2
3