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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值