1001 A+B Format (20point(s))
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
方法一:
将输入两数的加和结果一一存入数组,同时也按要求将 ',' 存入,最后输出数组即可。
为了方便处理,应该都认为正数处理,所以如果结果为负数可以先输出负号,再认为正数处理。
代码如下:
//
// Created by LittleCat on 2020/2/10.
//
#include <cstdio>
#include <algorithm>
using namespace std;
int main() {
int a, b;
scanf("%d %d", &a, &b);
int c = a + b;
if (c < 0) {
c = -c;
printf("-");
}
if (c == 0) {
printf("0\n");
return 0;
}
char ans[9] = {0};
int count = 0, len = 0;
/* 反向储存入数组中 */
while (c != 0) {
if (count % 3 == 0 && len != 0)
ans[len++] = ',';
count++;
ans[len++] = c % 10 + '0';
c = c / 10;
}
ans[len] = '\0';
reverse(ans, ans + len);
puts(ans);
}
方法二:
既然题给出了范围限定,那么最后结果最多就 7 位数,那么其实输出就只有三种情况,一一对号入座即可!
主要要注意逗号之后的输出要用0补齐,不然1000000 + 1000000 的结果会输出 2,0,0
代码如下:
//
// Created by LittleCat on 2020/2/10.
//
#include <cstdio>
int main() {
int a, b;
scanf("%d %d", &a, &b);
int c = a + b;
if (c < 0) {
c = -c;
printf("-");
}
if (c >= 1000000)
printf("%d,%03d,%03d\n", c / 1000000, c % 1000000 / 1000, c % 1000);
else if (c >= 1000)
printf("%d,%03d\n", c / 1000, c % 1000);
else
printf("%d\n", c);
}
end
欢迎关注个人公众号“ 鸡翅编程 ”,这里是认真且乖巧的码农一枚。
---- 做最乖巧的博客er,做最扎实的程序员 ----
旨在用心写好每一篇文章,平常会把笔记汇总成推送更新~