题目:
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
解题思路:
将两个数相加后的计算结果直接转换为 string 类型,然后从后往前遍历,每循环三次插入一个逗号。
虽然在 string 中间进行插入操作会消耗大量的时间,但题目中限定了数字的长度,因此不必考虑时间问题。
代码:
编译器:C++(g++)
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a,b;
cin>>a>>b;
int sum=a+b;
string str=to_string(sum);
int i=0;
if('-'==str[0])
{
i=1;
}
for(int j=str.size()-1,count=0;j>i;--j)
{
++count;
if(3==count)
{
str.insert(j,",");
count=0;
}
}
cout<<str<<endl;
return 0;
}