目录
题目标题
1001 A+B Format
题目描述
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).
输入描述
Each input file contains one test case. Each case contains a pair of integers a and b where −10^6≤a,b≤10^6. The numbers are separated by a space.
输出描述
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.
输入样例
-1000000 9
输出样例
-999,991
思路描述
从后往前数,每三个数字以一个','分开,同时注意,数字首部不能有逗号,如果是‘-’,数字的len需要减一。
Code
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int a,b;
cin>>a>>b;
int sum=a+b;
string s=to_string(sum);
int count=1;
reverse(s.begin(),s.end());
string t="";
int i=0;
int len=s.length();
if(s[s.length()-1]=='-')
len--;
for(i;i<len;i++)
{
t+=s[i];
if(count%3==0&&count!=len)
t+=",";
count++;
}
if(len!=s.length())
t+="-";
reverse(t.begin(),t.end());
cout<<t<<endl;
return 0;
}
提交结果
freetalk or label
easy