PAT 1001 A+B Format (20分)(转化字符串)第三次重刷PAT甲级题

本文介绍了PAT甲级题1001 A+B Format的题目要求,即计算a+b并按标准格式输出,数字间以逗号分隔。文章分享了一个使用Java解决此问题的思路,强调了如何处理数字分组和逗号插入,通过举例说明了输入输出规范。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

7月底就要考试了,四月份就立下雄心壮志要刷上甲级题5遍,如今到现在也才准备刚开始第三遍,丢人呐,最近也在刷力扣,那么就两个一起刷吧,希望七月底能有一个好成绩
不过现在PAT在线上考试了,不知道这次的含金量会降低不,

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

这道题20分我总是还要去看下之前写的代码,总是忘了什么时候写逗号,其实也比较容易,对于一个数,用长度与3取余,剩下的就是最前面的个数,而如果让i到了这个个数,就应该输出’,‘之后每过三个输出’,'直到结尾就完成了,所以就是用i也与3取余,第一次小于3时,输出逗号,之后每次又加3,所以与3取余后还是该数,不变。

#include<bits/stdc++.h>
using namespace std;
int main(){
    int a,b;
    cin>>a>>b;
    string c=to_string(a+b);
    for(int i=0;i<c.length();i++){
        cout<<c[i];
        if(c[i]=='-') continue;
        if(c.length()%3==(i+1)%3&&i!=c.length()-1) cout<<',';
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值