PAT Advanced 1001 A+B Format (20 分) c++语言实现(g++)

...刚发现这一系列题目的名称是PAT, 一直搞错了以为是PTA 虽然也没啥问题.哈哈哈哈 PTA是网站名字 ,PAT 是考试名字

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 −106​​a,b106​​. 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

 

计算a b 和 结果从个位数起每3个数字添加一个逗号',',  结果转字符串,然后倒叙从字符串最后一位开始每隔3个数字添加一个逗号, 然后翻转输出

需要注意一点 就是如果是负数 结果<0 的添加逗号的条件是 前面只剩下两位字符时不添加逗号

        而结果是正数时, 前面只剩下1位的情况下,不要添加逗号

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(){
    int count{0};//计数 每三个数字字符添加一个逗号
    long a,b;
    string temp,str;
    cin >> a >>b;
    a=a+b;
    temp=to_string(a);
    for(int i=temp.size()-1;i>=0;i--){
        count++;
        str.push_back(temp[i]);
        if((count%3==0)&&((i>1&&a<0)||(i>0&&a>0)))//正负数添加逗号判定不同
            str.push_back(',');
    }
    reverse(str.begin(),str.end());
    cout << str<<endl;
    return 0;
}

 

posted @ 2021-05-15 01:06  keiiha  阅读(57)  评论(0编辑  收藏  举报