PAT甲级1001. A+B Format

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Hacker_Wind/article/details/79944036

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

Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

Output

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
 
  
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include <queue>
#include <stack>
using namespace std;
//ios::sync_with_stdio(false);
//typedef long long ll;
const int MAXN = 100005;
//const int inf = 0x3f3f3f3f;


int main()
{
    int a,b;
    cin>>a>>b;
    int sum=a+b;
    int s;
    if(sum<0)
        s=-sum;
    else
        s=sum;
    stack<int> x;
    int t=0,h=0;
    if(sum<=999&&sum>=-999)
    {
        cout<<sum<<endl;
        return 0;
    }
    while(s!=0)
    {
        x.push(s%10);
        s/=10;
        h++;//记录数字个数
    }
    if(sum<0)
        cout<<"-";
    int flag=0;//判断剩余数字个数是否为3的倍数
    while(!x.empty())
    {
        if(h%3==0)
            flag=1;
        if(h%3!=0&&flag==0)
        {
            h--;
        }
        if(t==3&&flag==1)
        {
            cout<<",";
            t=0;
        }
        cout<<x.top();
        x.pop();
        if(flag==0&&h%3==0)
                cout<<",";
        if(flag==1)
        t++;
    }
    cout<<endl;

    return 0;
}

 

猜你喜欢

转载自blog.csdn.net/Hacker_Wind/article/details/79944036
今日推荐