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).
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
思路及代码
就是个格式的问题。整数肯定没办法处理,只能用字符串类型
那么关键是逗号的位置,在第i轮的时候,每隔三个数加个逗号,所以有i*3个数,有i-1个逗号。所以现在用str的length剪掉这些就是要加逗号的位置
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a,b;
cin>>a>>b;
string str = to_string(a+b);
for(int c = a+b,i=1;c/1000;c/=1000,i++)
str.insert(str.length() - i*3 -i+1, ",");
cout<<str;
}