PAT (Advanced Level) Practice 1001 A+B Format (20 分) 凌宸1642

这篇博客详细介绍了PAT(Advanced Level) Practice 1001A+B Format的解题思路和代码实现。题目要求计算两个整数的和,并按特定格式输出,即每三位一组,用逗号分隔。博主提供了C++代码示例,通过将数字转换为字符串,然后遍历添加逗号来完成格式化输出。

PAT (Advanced Level) Practice 1001 A+B Format (20 分) 凌宸1642

题目描述:

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).

译:计算 a + b 的和,并格式化输出——即,数字必须每三个作为一组,用逗号隔开(除非少一四位数字)


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.

译:每个输入文件包含一个测试用例,每个测试用例包含一个整数 a 和一个整数 b , 10-6 ≤ a , b ≤ 10 6 数字之间用空格分开。


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

The Idea:

/*
	根据 a 和 b 的范围知,int 完全够用  先计算 c = a + b 存储 a + b 的和,
	然后根据其的正负确定是否需要输出负号 “ - ”
	然后将 c 转成 string 类型,利用循环遍历一次,当从末尾且从1计数开始,如果这个位置是3的倍数
	意味着需要加一个逗号(string 的长度刚好是3的倍数时第一个除外) ;
	遍历完成之后,直接输出所得字符串即可
*/

The Codes:

#include<bits/stdc++.h>
using namespace std ;
int main(){
	int a , b , c ;
	cin >> a >> b ; 
	c = a + b ;
	string s , ans = "" ; 
	if(c < 0) ans += "-" ;
	s = to_string(abs(c)) ;
	for(int i = 0 ; i < s.size() ; i ++){
		if((s.size() - i) % 3 == 0 && i != 0) ans += "," ; // 加逗号的情况
		ans += s[i] ;
	}
	cout<< ans << endl ;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lingchen0522

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值