PAT (Advanced Level) Practice —1001 A+B Format (20 分)
题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805528788582400
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 −106≤a,b≤106. 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
我怀疑自己是不是脑子是不是有问题...
:题意 求两个数字相加的和并按格式输出和,格式规定,每隔3个数字要有一个 ',' 当然是从后往前啊 10,000 。开始我竟然写成了 cnt++,如果cnt==3,就输出逗号并且cnt再次初始化为0.....真的太蠢了!
:思路
- 将求出的和转化为字符串形式;
- index处理负数的情况;
- 判断剩下的数(len-1-i)是否是3的倍数,如果是,输出逗号,当然除了已到达字符末尾的情况不用输出逗号。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main(){
int a,b;
while(cin>>a>>b){
int sum=a+b;
char s[20];
sprintf(s,"%d",sum);
int len=strlen(s);
int index=0;
if(sum<0){
cout<<'-';
index=1;
}
int cnt=0;
for(int i=index;i<=len-1;i++){
cout<<s[i];
int left=len-1-i;
if(left%3==0&&i!=len-1){
cout<<',';
}
}
cout<<endl;
}
return 0;
}