概述
1001 A+B Format (20 point(s))
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
题解
对比多种方法后,参考了柳神的思路,因为tostring有点小问题,学习了下stringstream;简单理解为,传值转换,输出
(i+1)%3==len%3&&i!=len-1
这个公式不是很理解,但是i%3==0会有两个测试点无法通过
#include <iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
int a;
int b;
string result;
stringstream c;
cin>>a>>b;
c<<a+b;
c>>result;
int len=result.length();
for(int i=0;i<len;i++){
cout<<result[i];
if (result[i] == '-') continue;
if((i+1)%3==len%3&&i!=len-1) cout<<",";
}
return 0;
}
思路2:
柳神的算法有点看不懂,所以自己想了个,(len-(i+1))%3==0
,从末尾开始计数,满3就加逗号`
二刷更新,上述表达式不太好懂,可以写成
(len-1-i)%3==0
字符串长度减去正序遍历成为倒序遍历。
#include <iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
int a;
int b;
string result;
stringstream c;
cin>>a>>b;
c<<a+b;
c>>result;
int len=result.length();
for(int i=0;i<len;i++){
cout<<result[i];
if (result[i] == '-') continue;
// if((len-(i+1))%3==0&&i!=len-1)
f((len-1-i)%3==0&&i!=len-1)
cout<<",";
}
return 0;
}
`
最后
以上就是酷炫大门为你收集整理的PAT甲级1001A+BSample Input:Sample Output:的全部内容,希望文章能够帮你解决PAT甲级1001A+BSample Input:Sample Output:所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复