原题
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
大体翻译
两个范围为−106 ≤a,b≤106的数相加,要求输入和的标准形式
标准形式即为有正负号,如果这个数超过三位数,则需要三位为一组将其区分开
例如上述输出中的-999,991
整体思路
输入两个数a、b,得出其和c
先判断c是否为0,为0则显示0并结束
再判断c是否为负数,若为负数则输出负号‘-’
接着对c的绝对值进行输出:
先将每一位添入一位整数数组
此时数组中的数是相反的
例如:c为12345,那么数组中的数为a=[5,4,3,2,1]
因此要从数组的后面遍历数组,当下标是3的倍数且下标不为0时,在后面输出,
例如:下标为4时输出1,下标为3时输出2,此时是3的倍数,紧接着输出,
则最后结果为12,345
至于为什么在下标是3的倍数且不为0时,在后面输出,
,可以通过简单的举例找规律得出
例如:
1 2, 3 4 5, 6 7 8
7 6 5 4 3 2 1 0
第一次编写
代码如下:
#include <iostream>
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
int c;
c = a + b;
if (c < 0)
{
c = -c;
cout << "-";
}
if (c == 0)
{
cout << 0;
return 0;
}
int sum = c, num = 0, z[30] = { 0 };
while (sum > 0)
{
z[num++] = sum % 10;
sum = sum / 10;
//cout << z[num] <<" "<< sum<<endl;
}
for (int i = num - 1; i >= 0; i--)
{
cout << z[i];
if (i % 3 == 0&&i!=0)
cout << ",";
}
return 0;
}
结果: