【笨方法学PAT】1001 A+B Format(20 分)

版权声明:欢迎转载,请注明来源 https://blog.csdn.net/linghugoolge/article/details/82588211

一、题目

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

二、题目大意

按照英文数字样式,从后往前,每三位,加上”,”。

三、考点

string

PS. string 与 int 的互相转换,可以参考:【笨方法学PAT】string 与 int 的互相转换

四、解题思路

PAT数字类的题目,可以将数字转为string进行处理,之后再转回来。 
string与int的互相转换:

五、代码

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main() {
    int a, b;
    cin >> a >> b;
    int c = a + b;
    string s = "";

    //==0特殊处理
    if (c == 0) {
        cout << 0 << endl;
        return 0;
    }

    //<0预处理
    if (c < 0) {
        cout << "-";
        c = -c;
    }

    //转为string处理
    s = to_string(c);
    int cnt = 0;
    string t="";
    reverse(s.begin(), s.end());
    for (int i = 0; i < s.length(); i++) {
        t += s[i];
        if ((i+1) % 3 == 0&&i!=s.length()-1)
            t += ',';
    }
    reverse(t.begin(), t.end());

    //输出结果
    cout << t;
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/linghugoolge/article/details/82588211
今日推荐