Acwing 1473. A + B 格式

原题:

 

计算 a+b 并以标准格式输出总和----也就是说,从最低位开始每隔三位数加进一个逗号(千位分隔符),如果结果少于四位则不需添加。

输入格式

共一行,包含两个整数 a 和 b。

输出格式

共一行,以标准格式输出 a+b 的和。

数据范围

我的题解:

#include <iostream>

using namespace std;

int main()
{
    int a,b,c;
    cin>>a>>b;
    c=a+b;
    string tem;
    tem=to_string(c);
    string res;
    int i,j;
    for(i=tem.size()-1,j=0;i>=0;i--)
    {
        res=tem[i]+res;
        j++;
        if(j%3==0&&i&&tem[i-1]!='-')
        {
            res=','+res;
        }
    }
    cout<<res;
}
优秀题解:

#include <iostream>

using namespace std;

int main()
{
    int a, b;
    cin >> a >> b;
    int c = a + b;
    string num = to_string(c);
    string res;

    for (int i = num.size() - 1, j = 0; i >= 0; i -- )
    {
        res = num[i] + res;  // 每一次都是先把原字符串的当前位放进答案
        ++ j;               // 然后对于原字符串的这一位,在当前答案的下一位上是否该放','
        if (j % 3 == 0 && i && num[i - 1] != '-') res = ',' + res;
    }

    cout << res << endl;

    return 0;
}

作者:小张同学
链接:https://www.acwing.com/solution/content/10472/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值