您的位置:首页 > 其它

pat甲级1001. A+B Format (20)

2018-03-12 19:54 501 查看

1001. A+B Format (20)

时间限制400 ms
内存限制65536 kB
代码长度限制16000 B
判题程序Standard作者CHEN, Yue
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).InputEach input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.OutputFor 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

算法设计:

先用两个int型变量将两个数字读取进来,加和之后得到结果,判断该结果是否为负,如果是负值,先输出"-"号,然后将结果转化为正数,存到一个char型数组或string中。接下来有从前向后遍历和从后向前遍历两种方法输出:

从前向后遍历:

假设得到的char数组或者string长度为len,求出len%3的值,如果值不为0,假设为2,就先将前面这len%3位输出,剩下的就按照输出一个","再输出3位数字的形式输出;如果值为0,就先输出前面的三位,剩下的依然按照输出一个","再输出3位数字的形式输出即可。

c++代码:

#include<bits/stdc++.h>
using namespace std;
int main(){
int a,b;
scanf("%d%d",&a,&b);
a+=b;
if(a<0){
printf("-");
a=abs(a);
}
char temp[9];
sprintf(temp,"%d",a);
int len=strlen(temp),i=0;
a=len%3;
if(a==0)
a=3;
while(i<a){
printf("%c",temp[i]);
++i;
}
while(i<len){
printf(",");
for(int j=0;j<3;++j){
printf("%c",temp[i]);
++i;
}
}
return 0;
}

从后向前遍历:

从后向前遍历需要另外开辟一个vector空间,可将得到的char数组或者string以3位数字为一部分,一部分一部分地存储到vector中,如果遍历到char数组或者string前几位不够3位,就将这几位也存储到vector中,然后对vector中的元素倒序输出即可

c++代码:

#include <bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[])
{
long a,b;
cin>>a>>b;
a+=b;
if(a<0)
{
cout<<"-";
a=-a;
}
string s=to_string(a);
vector<string>v;
int i=s.size()-3;
for(;i>0;i-=3)
{
v.push_back(s.substr(i,3));
}
v.push_back(s.substr(0,i+3));
for(i=v.size()-1;i>0;--i)
{
cout<<v[i]<<",";
}
cout<<v[0]<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 string pat