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
题目大意:计算 a 和 b 的和并用标准格式输出,即数字必须用逗号分成三组(除非少于四位数)。
数据范围:-1000000 <= a, b <= 1000000
解题思路:数据范围比较小,开 int 就可以了。如果小于四位数直接输出。否则:先记录和的符号,对 10 取余把个位提取出来 +’0’ 转成字符存入字符数组,每三位加入一个逗号,最后逆序输出。
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 100+10;
const int INF = 0x3f3f3f3f;
int main() {
int a, b;
scanf("%d%d", &a, &b);
int c = a + b;
if (c < 1000 && c > -1000) printf("%d\n", c);
else {
int op = c >= 0 ? 1 : 0;
c = c > 0 ? c : -c;
int t = 0, cnt = 0;
char tmp[15];
while (c) {
if (cnt%3 == 0) {
tmp[t++] = ',';
cnt = 0;
}
tmp[t++] = (c % 10) + '0';
c /= 10;
cnt++;
}
if (!op) cout << "-";
for (int i = t-1; i > 0; i--) {
printf("%c", tmp[i]);
}
printf("\n");
}
return 0;
}
提交时间 | 状态 | 分数 | 题目 | 编译器 | 耗时 |
---|---|---|---|---|---|
2018/7/5 22:02:53 | 答案正确 | 20 | 1001 | C++ (g++) | 3 ms |