2288. 价格减免

2288. 价格减免


题目链接:2288. 价格减免

代码如下:

class Solution 
{
public:
    string discountPrices(string sentence, int discount) 
    {
        // stringstream默认按照空格分隔字符串
        stringstream ss(sentence);
        string res, word;
        // 一边分割,一边加到答案中
        while (ss >> word) 
        {
            if (!res.empty()) 
            {
                res += ' ';
            }
            if (word.size() > 1 && word[0] == '$' &&
                all_of(word.begin() + 1, word.end(), ::isdigit)) 
            {
                stringstream s;
                double price = stoll(word.substr(1, word.size() - 1)) *
                               (1.0 - discount / 100.0);
                // 想要保留数据的有效位数,需要用到setprecision() /
                // cout.precision()函数
                // 想要保留n为小数,需要加上cout.setf(ios::fixed); 或者cout <<
                // fixed或者cout<<setiosflags(ios::fixed)
                s << fixed << setprecision(2) << '$' << price;
                res += s.str();
            } else 
            {
                res += word;
            }
        }
        return res;
    }
};

相关推荐

  1. 2288. 价格减免

    2024-07-10 11:20:06       11 阅读
  2. LeetCode 2288.价格减免:模拟

    2024-07-10 11:20:06       15 阅读
  3. 【康复学习--LeetCode每日一题】2288. 价格减免

    2024-07-10 11:20:06       19 阅读
  4. [leetcode] 228. 汇总区间

    2024-07-10 11:20:06       23 阅读
  5. LeetCode 74, 228, 39

    2024-07-10 11:20:06       6 阅读
  6. LeetCode--2298. 周末任务计数

    2024-07-10 11:20:06       35 阅读
  7. leetcode-2788按分隔符拆分字符串

    2024-07-10 11:20:06       41 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-10 11:20:06       4 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-10 11:20:06       5 阅读
  3. 在Django里面运行非项目文件

    2024-07-10 11:20:06       4 阅读
  4. Python语言-面向对象

    2024-07-10 11:20:06       4 阅读

热门阅读

  1. Quartz 介绍

    2024-07-10 11:20:06       6 阅读
  2. Taro自定义实现本地路径转换为文件

    2024-07-10 11:20:06       7 阅读
  3. Python 类与对象:深入理解与应用

    2024-07-10 11:20:06       8 阅读
  4. 20240709每日后端--------Spring Boot的启动流程

    2024-07-10 11:20:06       9 阅读
  5. qt 播放相机的数据

    2024-07-10 11:20:06       11 阅读
  6. PHP的发展历程以及功能使用场景

    2024-07-10 11:20:06       8 阅读
  7. Redis哨兵模式与集群模式的快速部署

    2024-07-10 11:20:06       7 阅读