Skip to content

2288. Apply Discount to Prices 👎

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
 public:
  string discountPrices(string sentence, int discount) {
    constexpr int kPrecision = 2;
    string ans;
    istringstream iss(sentence);

    for (string word; iss >> word;)
      if (word[0] == '$' && word.length() > 1) {
        const string digits = word.substr(1);
        if (ranges::all_of(digits,
                           [](const char digit) { return isdigit(digit); })) {
          const double val = stold(digits) * (100 - discount) / 100;
          const string s = to_string(val);
          const string trimmed = s.substr(0, s.find(".") + kPrecision + 1);
          ans += "$" + trimmed + " ";
        } else {
          ans += word + " ";
        }
      } else {
        ans += word + " ";
      }

    ans.pop_back();
    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public String discountPrices(String sentence, int discount) {
    final int kPrecision = 2;
    StringBuilder sb = new StringBuilder();

    for (final String word : sentence.split(" "))
      if (word.charAt(0) == '$' && word.length() > 1) {
        final String digits = word.substring(1);
        if (digits.chars().allMatch(c -> Character.isDigit(c))) {
          final double val = Double.parseDouble(digits) * (100 - discount) / 100;
          final String s = String.format("%.2f", val);
          final String trimmed = s.substring(0, s.indexOf(".") + kPrecision + 1);
          sb.append("$").append(trimmed).append(" ");
        } else {
          sb.append(word).append(" ");
        }
      } else {
        sb.append(word).append(" ");
      }

    sb.deleteCharAt(sb.length() - 1);
    return sb.toString();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def discountPrices(self, sentence: str, discount: int) -> str:
    kPrecision = 2
    ans = []

    for word in sentence.split():
      if word[0] == '$' and len(word) > 1:
        digits = word[1:]
        if all(digit.isdigit() for digit in digits):
          val = float(digits) * (100 - discount) / 100
          s = f'{val:.2f}'
          trimmed = s[:s.index('.') + kPrecision + 1]
          ans.append('$' + trimmed)
        else:
          ans.append(word)
      else:
        ans.append(word)

    return ' '.join(ans)