# 甲级PAT1001 A+B Format

1001 A+B Format (20)（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

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``

## 注意：

1.位数少于三位直接输出

2.若余数恰好为0，此时的开始位置要为3而不是0，这点一定要注意。

3.正负的处理不同，是因为负数要比正数多一个负号。因此可以先通过erase()函数去掉负号，同正数一起处理即可。最后按格式保存后再把负号加上就可以了。

## 完整代码：

``````#include<iostream>
#include <sstream>
#include<string>
using namespace std;

int main(){
int a,b,sum;
stringstream ss;
string s,result;
int i,x,y;
result = "";
cin>>a>>b;
sum = a + b;
ss << sum;
ss >> s;
if(sum>=0){
x = s.length()/3;
y = s.length()%3;
if(x<1){
cout<<s<<endl;
}else if(y==0){
for(i=3;i<=s.length()-3;i=i+4){
s.insert(i,",");
}
cout<<s<<endl;
}else{
for(i=y;i<=s.length()-3;i=i+4){
s.insert(i,",",1);
}
cout<<s<<endl;
}
}else{
s.erase(0,1);
x = s.length()/3;
y = s.length()%3;
if(x<1){
s.insert(0,"-");
cout<<s<<endl;
}else if(y==0){
for(i=3;i<=s.length()-3;i=i+4){
s.insert(i,",");
}
s.insert(0,"-");
cout<<s<<endl;
}else{
for(i=y;i<=s.length()-3;i=i+4){
s.insert(i,",",1);
}
s.insert(0,"-");
cout<<s<<endl;
}
}
return 0;
}``````

## 笔记：

1.int型和long long型的范围

int                  所占字节数为:4                   表示范围为：-2147483648~2147483647

long long 　　  所占字节数为:8　　　　　　　表示范围为：9223372036854775808～+9223372036854775807

2.stringstream类

本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。