题目 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.
解析
两个整数相加,结果以三位为一组逗号分隔
源码
https://github.com/vlluvia/pat
代码
旧代码
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
void pat1001(){
int a,b;
int i=0;
char res[10][5]={""};
cin>>a>>b;
int re = a+b;
if (re<0){
strcat(res[i],"-");
++i;
re = abs(re);
}
while(re/1000>0){
char r[4] ="";
char t[4]=",";
char l[4] = "";
if ((re%1000)/100 == 0){
strcat(l,"0");
if ((re%100)/10 == 0){
strcat(l,"0");
if ((re%10) == 0){
strcat(l,"0");
}else{
snprintf(r, sizeof(r), "%d", re%1000);
}
}else{
snprintf(r, sizeof(r), "%d", re%1000);
}
} else{
snprintf(r, sizeof(r), "%d", re%1000);
}
strcat(l,r);
strcat(t,l);
strcat(res[i],t);
re/=1000;
++i;
}
char r[4] = "";
snprintf(r, sizeof(r), "%d", re);
strcat(res[i],r);
++i;
char o[15]="";
if (a+b<0) {
strcat(o, res[0]);
for (int j = i-1; j > 0; --j) {
strcat(o, res[j]);
}
} else{
for (int j = i-1; j >= 0; --j) {
strcat(o, res[j]);
}
}
cout<<o<<endl;
}
int main() {
pat1001();
return 0;
}
新代码
#include<bits/stdc++.h>
#define INF 1<<30
using namespace std;
void pat1001() {
long a, b;
cin >> a >> b;
long c = a + b;
if (c > -1000 && c < 1000) {
cout << c << endl;
} else if (c > -1000000 && c < 1000000) {
printf("%d,%03d", c / 1000, abs(c % 1000));
} else {
printf("%d,%03d,%03d", c / 1000000, abs(c % 1000000 / 1000), abs(c % 1000));
}
}
int main() {
pat1001();
return 0;
}