PAT (Advanced Level) 1001 A+B Format (20 分)

序:
这是一道关于字符串处理的题。

Calculate a+b and output the sum in standard format – that is, the digits must be separated into groups of three by commas (unless there are less than four digits).

Input Specification:

Each input file contains one test case. Each case contains a pair of integers a and b where −10​6​​≤a,b≤10​6​​. The numbers are separated by a space.

Output Specification:

For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.

Sample Input:

-1000000 9

Sample Output:

-999,991

题目概述:
把两数相加后的结果按照从后到前三位一个逗号的格式输出。

分析:
1.将int转为string方便处理
2.将原结果的str1从后往前遍历,每三个数位加一个’,’(注意首位不加),并将该结果写入str2
3.str2反转后即为所求

//从后到前加,
#include<bits/stdc++.h>
using namespace std;

int main()
{
    int a, b;
    scanf("%d%d", &a, &b);
    int sum = a + b;
    if(sum < 0) printf("-");
    string str1 = to_string(abs(sum));
    string str2;
    for(int i = 0; i < str1.size(); i++)
    {
        str2 += str1[str1.size() - 1 - i];
        if((i + 1) % 3 == 0 && i != str1.size() - 1) str2 += ',';
    }
    reverse(str2.begin(),str2.end());
    printf("%s", str2.c_str());
    printf("\n");
    return 0;
}

总结:
这道题一开始debug了半天,通过测试样例发现原来我写的逗号是从前往后加的,直接傻了。。。所以,还是想清楚题目要求再编码!

续。2022.01.07代码:

#include<bits/stdc++.h>
using namespace std;

string format(int num) {
    // 提取负号
    bool isNegative = false;
    if(num < 0) {
        isNegative = true;
        num = abs(num);
    }
    //反向找num
    string res = "";
    string mynum = to_string(num);
    int cnt = 0;
    //每三个加逗号
    for(int i = mynum.size() - 1; i >= 0; i--) {
        if(cnt % 3 != 0 || i == mynum.size() - 1)
            res += mynum[i];
        else {
            res += ',';
            res += mynum[i];
        }
        ++cnt;
    }
    //反向结果
    reverse(res.begin(), res.end());
    //加负号
    if (isNegative)
        res = "-" + res;
    return res;
}

int main() {
    int a, b;
    cin >> a >> b;
    cout << format(a + b) << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

白速龙王的回眸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值