0
点赞
收藏
分享

微信扫一扫

【PAT甲】1001 A+B Format (20分) 格式化输出


problem

1001 A+B Format (20分)
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

  • 将两个数字相加,用标准格式输出最终结果

solution

  • 两数相加开始还以为是高精度有点烦,结果1e6的数据怎么加都不会超过int的。
  • 标准格式输出,想用string流但是不会(而且慢),想用除法和取模发现循环顺序不对,最后用了递归。(分三步优化)
  • 提交WA了第四个点,考虑特殊数据 0 0时没有输出

#include<iostream>
using namespace std;
void output(int c, int cnt){
if(!c)return ;
if(cnt%3==0 && c/10!=0){
output(c/10,cnt+1);
cout<<",";
}else output(c/10,cnt+1);
cout<<c%10;
}
int main(){
int a, b;
cin>>a>>b;
int c = a+b;
if(c==0){
cout<<0<<endl;
return 0;
}
if(c<0){
cout<<"-";
c = -c;
}
output(c,1);
return 0;
}


举报

相关推荐

0 条评论