分数 20
全屏浏览题目
切换布局
作者 CHEN, Yue
单位 浙江大学
Consider a positive integer N written in standard notation with k+1 digits ai as ak⋯a1a0 with 0≤ai<10 for all i and ak>0. Then N is palindromic if and only if ai=ak−i for all i. Zero is written 0 and is also palindromic by definition.
Non-palindromic numbers can be paired with palindromic ones via a series of operations. First, the non-palindromic number is reversed and the result is added to the original number. If the result is not a palindromic number, this is repeated until it gives a palindromic number. Such number is called a delayed palindrome. (Quoted from https://en.wikipedia.org/wiki/Palindromic_number )
Given any positive integer, you are supposed to find its paired palindromic number.
Input Specification:
Each input file contains one test case which gives a positive integer no more than 1000 digits.
Output Specification:
For each test case, print line by line the process of finding the palindromic number. The format of each line is the following:
A + B = C
where A
is the original number, B
is the reversed A
, and C
is their sum. A
starts being the input number, and this process ends until C
becomes a palindromic number -- in this case we print in the last line C is a palindromic number.
; or if a palindromic number cannot be found in 10 iterations, print Not found in 10 iterations.
instead.
Sample Input 1:
97152
Sample Output 1:
97152 + 25179 = 122331
122331 + 133221 = 255552
255552 is a palindromic number.
Sample Input 2:
196
Sample Output 2:
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.
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include<bits/stdc++.h>
using namespace std;
string add(string a,string b){//将a,b换成十进制相加
int cc=0,len=a.size();//cc表示进位一开始为0
string t;
for(int i=len-1;i>=0;i--){//从个位开始相加
int x=(a[i]-'0'+b[i]-'0'+cc)%10;//相加取低位
cc=(a[i]-'0'+b[i]-'0'+cc)/10;//每次的进位
t=to_string(x)+t;//将每次的低位以字符串形式保存在t里
}
if(cc==1)t="1"+t;//最后一次的进位为1则加上
return t;
}
bool ispal(string s){//判断是否为回文数
int len=s.size();
for(int i=0;i<len;i++){
if(s[i]!=s[len-1-i])return false;
}
return true;
}
int main(){
string s;
cin>>s;
if(ispal(s)){//若输入的数就是回文数则直接输出
printf("%s is a palindromic number.\n",s.c_str());
return 0;
}
for(int i=1;i<=10;i++){//否则
string ss=s;
reverse(ss.begin(),ss.end());//得到s的反转
string res=add(s,ss);//将s和ss相加
printf("%s + %s = %s\n",s.c_str(),ss.c_str(),res.c_str());//输出
if(ispal(res)){//若是回文数则输出并中断
printf("%s is a palindromic number.\n",res.c_str());
break;
}
if(i==10)cout<<"Not found in 10 iterations."<<endl;//如果第十次还不是回文数则输出
s=res;//更新s
}
return 0;
}