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

举报
小哈里 发表于 2022/05/11 00:08:57 2022/05/11
【摘要】 problem 1001 A+B Format (20分) Calculate a+b and output the sum in standard format – that is, the digi...

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;
}


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

文章来源: gwj1314.blog.csdn.net,作者:小哈里,版权归原作者所有,如需转载,请联系作者。

原文链接:gwj1314.blog.csdn.net/article/details/108399033

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。