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

题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805528788582400

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 −. 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 #include <iostream>
 2 #include <cstdio>
 3 #include <string>
 4 #include <cstring>
 5 #include <algorithm>
 6 #include <stack>
 7 using namespace std;
 8 int main()
 9 {
10        int n,m,sum;
11        while(cin>>n>>m){
12            sum=n+m;
13            if(sum==0){
14                cout<<0<<endl;
15                continue;
16            }
17            int flag=0;
18            if(sum<0){
19            flag=1;
20            sum=-sum;
21            } 
22            char c='-';
23            stack<char> s;
24            int t=0;
25            while(sum){
26                c=sum%10+'0';
27                s.push(c);
28                t++;
29                if(t%3==0&&sum/10) s.push(',');
30                sum/=10;
31            }
32            if(flag) s.push('-');
33            while(!s.empty()){
34                cout<<s.top();
35             s.pop(); 
36            }
37            cout<<endl;
38        }
39     return 0;
40 }
 
posted @ 2019-04-25 18:50  wydxry  阅读(337)  评论(0编辑  收藏  举报
Live2D