A1001 A+B Format

A1001 A+B Format

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 −10^​6≤a,b≤10^6. 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

Code:

//参考了柳婼的代码
#pragma warning(disable: 4996)
#include <cstdio>
#include <cstdlib>
#include <cstring>

using namespace std;

int main(int argc, char *argv[]) {
long a, b;
scanf("%ld %ld", &a, &b);
char c[15];
sprintf(c, "%d", a + b);
int len = strlen(c);
for (int i = 0; i < len; i++) {
printf("%c", c[i]);
if (c[i] == '-') continue;//其实只需要排除「-,」这种情况负号就不会影响逗号
if (i % 3 == (len - 1) % 3 && i != len - 1) printf(",");
}//核心是这里的当前位数对3取余和总长度对3取余相等,很好理解
system("pause");
return 0;
}
//我的写法思路简单但写起来复杂
#pragma warning(disable: 4996)
#include <cstdio>
#include <cstdlib>
#include <cstring>

using namespace std;

int main(int argc, char *argv[]) {
long a, b, i = 0;
scanf("%ld %ld", &a, &b);
char c[15];
sprintf(c, "%d", a + b);//!!!
if (c[0] == '-') {
printf("-");
strcpy(c, c + 1);
}
int len1 = strlen(c);
int len2 = len1 % 3;
for (; i < len2; i++)
printf("%c", c[i]);
if (i != len1 && i != 0)
printf(",");
for (; i < len1; i = i + 3) {
for (int j = 0; j < 3; j++)
printf("%c", c[i + j]);
if (i + 3 < len1)
printf(",");
}

system("pause");
return 0;
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×