1001. A+B Format (20)
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
Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.
Output
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
#include <vector>
#include <iostream>
using namespace std;
int abs(int num){ //c++中的基本函数还是可以用的
return (num >= 0) ? num : (-num);
}
vector<char> breakFunc(int input){
vector<char> res; //用向量,是个不明智之举,很明显这是一个先入后出的数据模型,因此需要用到栈
int temp = abs(input);
int flag=0;
while (temp / 10 > 0){
flag++;
res.push_back((char)(temp % 10) + '0');
if ((flag % 3)== 0) //由于考虑不周全,这里最开始用的是 flag%3==0;然后改成了flag%3==0 || flag%6==0;还是不能全对
{
res.push_back('\,'); //这里转义字符要用\,
}
temp /= 10; //一度纠结flag++及前三个代码段的位置,完全是通过debug凑出来的,由此可见,提前思考清楚代码算法的逻辑是多重要
}
res.push_back((char)temp + '0'); //拉过这一步,总是少一个数字。
return res;
}
int main(){
int a, b,c;
while (cin >> a >> b){ //固定输入格式,关键:下面的这些代码块要放到循环语句中,而不是外面
c = a + b;
vector<char> res = breakFunc(c);
if (a >= 0) //未考虑a=0的情况
{
for (int i = res.size() - 1; i >= 0; i--) //vector逆向输出的方法,注意i>=0(i>0会拉掉一位数字)及i = res.size() - 1(i=res.size()会导致数组越界)
{
cout << res[i];
}
}
else
{
cout << "-";
for (int i = res.size() - 1; i >= 0; i--)
{
cout << res[i];
}
}
}
return 0;
}