PAT Advanced 1001

Posted yxp400

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT Advanced 1001相关的知识,希望对你有一定的参考价值。

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,b10?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

这道题刚开始脑袋木了一下没有理解题意,其实题目还是很简单的。
提供两种思路
1.(通用方法)直接将数字转化为字符串进行操作
#include<iostream>
#include<sstream>
#include<string>
using namespace std;
int main(){
	long long int a,b;
	string c;
	cin>>a>>b;
	a += b;
	stringstream s1;
	s1<<a;
	s1>>c;
	int num = c.length();
	for( int i = 0; i < num; i++){
		cout<<c[i];
		if(c[i] == ‘-‘)
			continue;
		else if((num-i-1)%3 == 0&& (num-i-1) != 0)
			cout<<",";
	} 
	return 0;
} 

  2.第二种方法是在网上无意中看到的,感觉也非常好,分享一下。

    鉴于题目的数据范围已经给定,其实最多只有7位数,那么就分以下几种情况:

    1.结果小于1000,无需,

    2.结果大于 1000 小于 1,000,000,需要一个逗号,

    3.结果大于 1,000,000,需要两个逗号。

    

 1 #include<iostream>
 2 #include<math.h>
 3 #include<string>
 4 using namespace std;
 5 
 6 int main(){
 7     long long int a,b;
 8     cin>>a>>b;
 9     a+=b;
10     if( a < 0 ){
11         cout<<"-";
12         a = fabs(a);
13     }
14     if( a < 1000)
15         cout<<a;
16     else if( a < 1000000)
17         printf("%d,%03d",a/1000,a%1000);
18     else
19         printf("%d,%03d,%03d",a/1000000,a%1000000/1000,a%1000);
20     return 0;
21 }

注意:输出时因为两个逗号之间经过处理后的数可能为0,所以要用%03d输出,保证数位正确。






以上是关于PAT Advanced 1001的主要内容,如果未能解决你的问题,请参考以下文章

PAT Advanced 1001 A+B Format (20 分) c++语言实现(g++)

PAT练习题目录

PAT (Advanced Level) 1075. PAT Judge (25)

PAT (Advanced Level) 1025 PAT Ranking

1093. Count PAT's (25)计数——PAT (Advanced Level) Practise

PAT (Advanced Level) 1075 PAT Judge