PAT1001A+B Format

时间:2023-03-08 16:55:34

链接:https://www.patest.cn/contests/pat-a-practise/1001

时间限制
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

思路:使用C++中的stringstream来进行整数与字符串的转换,头文件为<sstream>,先直接进行数值计算,然后转化为字符串,使用string中的insert()函数来插入逗号,最好从后往前进行插入,对于负数需要注意一下,以免在负号和数值中插入了逗号。

#include<cstdio>
#include<string>
#include<iostream>
#include<sstream> using namespace std; int main(){
int a,b,c;
while(~scanf("%d%d",&a,&b)){
c=a+b;
stringstream ss;
ss<<c;
string ans;
ss>>ans;
for(int i=ans.length()-3;i>0;i-=3){
if(ans[i-1]=='-') continue;
ans.insert(i,",");
}
cout<<ans<<endl;
}
return 0;
}