PAT甲级辅导课笔记(一)

第一讲:字符串处理(一)

课程介绍:主要讲解PAT甲级的题目(中文题面)。(为提升英语阅读水平可以去PAT读原题)

评测说明:AcWing评测机对于输出格式(行末空格等)的处理没有要求,而PAT的评测机要求比较严格。

字符串处理是PAT的常考题型,考察细心程度,需要熟悉C++字符串相关的API。

T1:1473. A + B 格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
计算 a+b 并以标准格式输出总和----也就是说,从最低位开始每隔三位数加进一个逗号(千位分隔符),如果结果少于四位则不需添加。

输入格式
共一行,包含两个整数 a 和 b。

输出格式
共一行,以标准格式输出 a+b 的和。

数据范围
10^6≤a,b≤10^6
输入样例:
-1000000 9
输出样例:
-999,991

AcWing:1473. A + B 格式PAT:1001 A+B Format

题解一:用to_string

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main(){
int a,b;
cin >> a >> b;

string str = to_string(a+b);

string s;
for (int i = str.size()-1,j = 0;i >= 0;i --){
s = str[i] + s;
j ++;
if (j % 3 == 0 && i && str[i-1] != '-') s = ',' + s;
}
cout << s;
return 0;
}

本题用到to_string函数,用于将非string数据转化为string类型。

题解二:不用to_string

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main(){
int a,b,c;
cin >> a >> b;
c = abs(a + b);
string str;
while (c){
str = char(c % 10 + '0') + str;
c /= 10;
}
if (a+b < 0) str = '-' + str;
// string str = to_string(a+b);

string s;
for (int i = str.size()-1,j = 0;i >= 0;i --){
s = str[i] + s;
j ++;
if (j % 3 == 0 && i && str[i-1] != '-') s = ',' + s;
}
if (!(a+b)) cout << 0;
else cout << s;
return 0;
}
坚持原创技术分享,您的支持将鼓励我继续创作!