PAT_A1136
PAT甲级1136.
目录
A1136
题目
样例
样例1
输入:
97152
输出:
97152 + 25179 = 122331
122331 + 133221 = 255552
255552 is a palindromic number.
样例2
输入:
196
输出:
196 + 691 = 887
887 + 788 = 1675
1675 + 5761 = 7436
7436 + 6347 = 13783
13783 + 38731 = 52514
52514 + 41525 = 94039
94039 + 93049 = 187088
187088 + 880781 = 1067869
1067869 + 9687601 = 10755470
10755470 + 07455701 = 18211171
Not found in 10 iterations.
思路和坑点
思路:
第一个是需要判定是不是回文数,判断字符串对称即可,另一个是要做字符串的相加处理,都属于常规操作。
坑点:
要注意对输入的数字进行判定,如果一开始就是回文数,则直接输出。
AC代码
#include<bits/stdc++.h>
using namespace std;
bool ishw(string &s); //判定是不是回文数
void add(string &s); //两个数字相加
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif
string s;
cin>>s;
if(s.size()==1||ishw(s)) { //如果只有一个字符,或者本身已经是回文数,直接输出
cout<<s<<" is a palindromic number.";
}
else{
int cnt=10;
while(cnt--){ //在规定次数内进行判定
add(s); //做一次相加处理
if(ishw(s)){
cout<<s<<" is a palindromic number.";
return 0;
}
}
puts("Not found in 10 iterations."); //如果在有限次数内没有产生回文数,则按照要求输出对应信息
}
return 0;
}
bool ishw(string &s) //判断回文
{
int i=0,j=s.size()-1;
while(i<j){
if(s[i]!=s[j])
return false;
i++,j--;
}
return true;
}
void add(string &s) //字符串相加
{
string temp=s;
reverse(temp.begin(),temp.end()); //逆转字符串
cout<<s<<" + "<<temp<<" = "; //输出相加的两个字符串
int flag=0; //进位
for(int i=0;i<s.size();i++){
int num=s[i]-'0'+temp[i]-'0'+flag;
s[i]='0'+num%10;
flag=num/10;
}
if(flag) s.push_back('0'+flag); //如果最高位仍然有进位
reverse(s.begin(),s.end()); //将最后形成的字符串按照正确的顺序返回
cout<<s<<'\n';
}