PAT A1136 A Delayed Palindrome(C++)

PAT甲级目录 | PAT乙级目录

题目描述

原题地址:A1136 A Delayed Palindrome
中文版:B1079 延迟的回文数

解题思路

判断回文数可以用字符串逆转的方法。字符串逆转后和原字符串相同,则为回文数,否则不是。

易错点

  • 初始给的 A 有可能为回文数,需要特判

也许陌生的知识点

  • ans = ans + "某字符串"
    • 字符串拼接
    • 需要的头文件:string
  • to_string()
    • 实现将一个数转换为字符串,这个数可以是整型或浮点型
    • 需要的头文件: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
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(){
string A;
cin >> A;
int cnt = 0;
while(cnt < 10){
string B = A, C;
reverse(B.begin(), B.end());
if(B == A){
cout << A << " is a palindromic number." << endl;
break;
}
int r = 0;
for(int i = 0; i < A.length(); i++){
int temp = r + (int)(A[i] + B[i] - 2 * '0');
C += to_string(temp % 10);
r = temp / 10;
}
if(r != 0) C += to_string(r);
string RC = C;
reverse(C.begin(), C.end());
cout << A + " + " + B + " = " + C << endl;
if(C == RC){
cout << C + " is a palindromic number." << endl;
break;
}else if(cnt + 1 == 10){
cout << "Not found in 10 iterations." << endl;
}
A = C;
cnt++;
}
return 0;
}