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
题目大意:给你两个数a,b让你求出a+b的值,并且把这个值按每三个数字用一个‘,’来分隔得格式输出结果,主要是格式问题。 但要注意当两个数相加结果为0的情况,我就忽视了这个点,然后第4个测试点一直过不了,找了很久才发现。负号一开始先不用考虑,最后添加上就行,一开始可以将相加的结果取绝对值,对绝对值进行处理。
accept code:
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
string str="",temp="",revtemp="";
string InttoChar(int s)//将整型转化为字符串型的函数
{
while(s!=0){
int r=s%10;
s=s/10;
temp+=(r+'0');
}
return temp;
}
string charreverse(string s){//对转化后的字符串进行翻转处理的函数
revtemp="";
for(int i=s.length()-1;i>=0;i--){
revtemp+=s[i];
}
return revtemp;
}
string compactchar(string s){//对反转后的字符串格式化的函数
int count=0;
for(int j=s.length()-1;j>=0;j--){
if(count==3){
count=0;
str+=',';
j+=1;
}
else{
str+=s[j];
count++;
}
}
str=charreverse(str);
return str;
}
int main()
{
int sum=0;
string s1,s2,s3;
int a,b;
cin>>a>>b;
sum=a+b;
if(sum==0)
{
cout<<0<<endl;
}
else if(sum<0){//判断是否加“-”
sum=abs(sum);
s1=InttoChar(sum);
s2=charreverse(s1);
s3=compactchar(s2);
cout<<'-'<<s3<<endl;
}
else{
s1=InttoChar(sum);
s2=charreverse(s1);
s3=compactchar(s2);
cout<<s3<<endl;
}
return 0;
}