1001. A+B Format (20)
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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
这题我的做法是字符串处理。一开始理解错了题意,以为是从前往后每出三位数字就出一个逗号,比如:1000输出为100,0,实际上应该是1,000
然后20分只拿到14分= =(SB样例根本看不出来啊)后来把输出逗号的判断由
cnt%3==0;
改为
(length-cnt)%3==0;length是结果字符串的长度
然后就过了。。。。下面贴代码:
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
int main()
{
int a,b;
char result[100]={0};//保留结果(其实开7个就足够了)
cin>>a>>b;
int sum=a+b,j=0;
if(sum<0)cout<<'-';//小于0
int sum1=fabs(sum);//取绝对值
if(sum==0)cout<<0<<endl;//对于0情况的特判
else
{
while(sum1)//将结果转为字符串
{
result[j++]=(sum1%10+'0');
sum1/=10;
}
int cnt=0;//统计输出了多少位
for(int i=j-1;i>=0;i--)
{
if((j-cnt)%3==0&&cnt)//输出逗号的情况
cout<<',';
cnt++;//加一位
cout<<result[i];
}
cout<<endl;
}
}
然而其实我这个方法复杂了,因为题中的数据范围只是正负一百万,也就是最多只有两个逗号输出。所以只需要三个if条件句输出即可==。但是我这种方法还是可以处理更高位数的对不对?理直气壮.JPG ,下面放方法二的代码:
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
int a,b;
cin>>a>>b;
int sum=a+b;
if(sum<0)cout<<'-';
sum=fabs(sum);
if(sum>=1000000)
//注意控制字段长度,比如001的输出,不足补‘0’;
cout<<sum/1000000<<','<<setfill('0')<<setw(3)<<sum/1000%1000<<','<<setfill('0')<<setw(3)<<sum%1000<<endl;
else if(sum>=1000)
cout<<sum/1000<<','<<setfill('0')<<setw(3)<<sum%1000<<endl;
else cout<<sum<<endl;
}