题外话:好久好久好久没有刷甲级的题目了,十分愧疚,从今天起,坚持打卡。
题目如下
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
思路分析:数字按格式转化成字符串,利用w记录长度并判断是否加入‘,’。
代码如下:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a, b, sum, sign = 1, w = 1;
string ans;
cin >> a >> b;
sum = a + b;
if (sum == 0) ans.push_back('0');
else
{
if (sum < 0) { sign = 0; sum *= -1; }
while (w <= sum) w *= 10; w /= 10;
if (sign == 0) ans.push_back('-');
while (w)
{
int temp = sum / w;
if (w == 1000 || w == 1000000) { ans.push_back('0' + temp); ans.push_back(','); }
else ans.push_back('0' + temp);
sum -= sum / w * w;
w /= 10;
}
}
cout << ans;
return 0;
}