一、题目描述
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 1 0 − 6 ≤ a , b ≤ 1 0 6 10^{-6}\leq a, b \leq10^6 10−6≤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
二、解题思路
根据题目给出的范围,我们可以用int,也可以用long long来定义变量,一开始,为了保险起见,我用的是long long。事实上,题目的加法就是简单的两个整数相加,所以我们要考虑的就是怎么把一个整数改写成题目所要求的的形式。由于当时的自己还非常年轻及幼稚,稍微绕了一些弯路。但是总的思想就是把负号拿出来单独考虑,每隔三个字符,插入一个逗号,最后把总的字符串打印出来。
三、AC代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
LL to_num(string str)
{
LL re = 0;
int sze = str.size();
if(str[0] == '-')
{
for(int i=1; i<sze; i++)
{
re = re*10 + str[i] - '0';
}
re = -re;
}
else
{
for(int i=0; i<sze; i++)
{
re = re*10 + str[i] - '0';
}
}
return re;
}
int main()
{
string a, b;
LL A, B, re;
cin >> a >> b;
A = to_num(a);
B = to_num(b);
re = A + B;
string ans;
ans = to_string(re);
if(re < 0)
{
printf("-");
ans.erase(ans.begin());
}
reverse(ans.begin(), ans.end());
int i = 0;
int sze = ans.size();
while(i+3 < sze)
{
i += 3;
ans.insert(ans.begin()+i, ',');
sze++;
i++;
}
for(int j=sze-1; j>=0; j--)
{
cout << ans[j];
}
cout << endl;
return 0;
}
四、思想改进
事实上,我们只需设置一个标志数组mk[10],将和转换成字符串,然后从后向前遍历这个字符串,到该打逗号的地方,我们把对应的标志数组的数设为True,即mk[i] = true,但是这里要注意判断条件,当所遍历到的字符是最前面的一位数,或者是负数的时候,我们是不加逗号的,意识到这一点,我写出的代码如下:
五、最终代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
int main()
{
LL a, b;
bool mk[10] = {false};
scanf("%lld%lld", &a, &b);
string ans;
int sum = a+b;
ans = to_string(sum);
int sze = ans.size();
int cnt = 1;
for(int i=sze-1; i>=0; i--)
{
if(cnt == 3 && ans[i] != '-' && i != 0 && ans[i-1] != '-')
{
mk[i] = true;
cnt = 1;
}
else cnt++;
}
for(int i=0; i<sze; i++)
{
if(mk[i]) printf(",%c", ans[i]);
else printf("%c", ans[i]);
}
return 0;
}
显然,这比我一开始写的代码要简单一些,但仍然没有到非常精简,对于PAT的代码可以去看看柳婼学姐的文章。