题目描述:
A number that will be the same when it is written forwards or backwards is known as a Palindromic Number. For example, 1234321 is a palindromic number. All single digit numbers are palindromic numbers.
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. For example, if we start from 67, we can obtain a palindromic number in 2 steps: 67 + 76 = 143, and 143 + 341 = 484.
Given any positive integer N, you are supposed to find its paired palindromic number and the number of steps taken to find it.
代码:
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
struct bign{
int d[1000];
int len;
bign(){
memset(d,0,sizeof(d));
len=0;
}
};
bign change(char str[]){
bign a;
a.len=strlen(str);
for(int i=0;i<a.len;i++){
a.d[i]=str[a.len-i-1]-'0';
}
return a;
}
void print(bign a){
for(int i=a.len-1;i>=0;i--){
printf("%d",a.d[i]);
}
printf("\n");
}
bool Judge(bign a){//判断是否回文
for(int i=0;i<=a.len/2;i++){
if(a.d[i]!=a.d[a.len-1-i]){
return false;//对称位置不等,则一定不回文
}
}
return true;//回文
}
bign add(bign a,bign b){//高精度a+b
bign c;
int carry=0;//carry是进位
for(int i=0;i<a.len||i<b.len;i++){
int temp=a.d[i]+b.d[i]+carry;
c.d[c.len++]=temp%10;
carry=temp/10;
}
if(carry!=0){
c.d[c.len++]=carry;
}
return c;
}
int main(){
char str[1000];
int T,k=0;
scanf("%s %d",str,&T);//初始数字、操作次数上限
bign a=change(str);//将字符串转换为bign
while(k<T&&Judge(a)==false){//不超过操作次数上限且a非回文
bign b=a;
reverse(b.d,b.d+b.len);//将b倒置
a=add(a,b);//a=a+b
k++;//操作次数+1
}
print(a);
printf("%d\n",k);
system("pause");
return 0;
}