PAT (Advanced Level) Practice 1001 A+B Format
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 −106≤a,b≤106. 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
#include<iostream>
#include<cmath>
using namespace std;
int a[10];
char b[20];
int main()
{
int n,m,j,k,i,T;
int A,B,c;
cin>>A>>B;
c = A+B;
bool flag;
c>=0?flag=false:flag=true;//flag代表是否插入负号
c = abs(c);
if (c==0) //特判
{
cout<<"0"<<endl;
return 0;
}
j=0;
while (c)
{
a[j++] = c%10;
c/=10;
}
int sum=0;
int t=0;
for (i=0;i<j;i++)
{
sum++;
b[t++] = a[i]+'0';
if (sum==3 && (i+1<=j-1))
{
b[t++] = ',';
sum=0;
}
}
if (flag)
cout<<"-";
for (i=t-1;i>=0;i--)
cout<<b[i];
cout<<endl;
return 0;
}