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>//提供abs()
#include<algorithm>//提供reverse()
#include<string>
using namespace std;
int main()
{
long long a,b,sum;
cin>>a>>b;
sum=a+b;
int flag=0;
if(sum>=0)
flag=1;
else
flag=0;
sum=abs(sum);//先取绝对值
if(sum==0){
cout<<0<<endl;
return 0;
}
string s;
while(sum!=0){//转换为字符串
s+=(sum%10+'0');
sum/=10;
}
reverse(s.begin(),s.end());//倒置
int len=s.size(),LEN=s.size();//这里保存LEN,因为len在后续过程中不断变化
//cout<<s.size()<<endl;
int t=3;
while(len>3){//每三位插入一个逗号
s.insert(LEN-t,",");//这里需注意,如果为len的话会出错,因为len是不断变化的
len-=3;
t+=3;
}
if(flag){
cout<<s<<endl;
}
else{
cout<<"-"<<s<<endl;
}
return 0;
}
代码有些AC的意思,暂时没想出鲁棒性强的代码,后续有待思考