1024 Palindromic Number分数 25
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.
向前或向后书写时相同的数字被称为回文数。例如,1234321是一个回文数字。所有的个位数都是回文数。
非回文数可以通过一系列运算与回文数配对。首先,将非回文数反转,并将结果添加到原始数上。如果结果不是回文数,则重复此操作,直到它给出回文数为止。例如,如果我们从67开始,我们可以分两步得到一个回文数:67+76=143,143+341=484。
给定任何正整数N,你应该找到它的配对回文数和找到它所需的步骤数。
Input Specification:
Each input file contains one test case. Each case consists of two positive numbers N and K, where N (≤1010) is the initial numer and K (≤100) is the maximum number of steps. The numbers are separated by a space.
每个输入文件包含一个测试用例。每种情况由两个正数N和K组成,其中N(≤1010)是初始数字,K(≤100)是最大步数。这些数字用空格隔开。
Output Specification:
For each test case, output two numbers, one in each line. The first number is the paired palindromic number of N, and the second number is the number of steps taken to find the palindromic number. If the palindromic number is not found after K steps, just output the number obtained at the Kth step and K instead.
对于每个测试用例,输出两个数字,每行一个。第一个数字是N的成对回文数,第二个数字是找到回文数所需的步骤数。如果在K步之后没有找到回文数,只需输出在第K步获得的数字和K。
Sample Input 1:
67 3
Sample Output 1:
484
2
Sample Input 2:
69 3
Sample Output 2:
1353
3
//在执行步骤100次后。结果已经超过longlong型了,要采用大整数型bign
//1.定义大整数结构体 2.将输入的整数字符串放在大整数中 3.定义add加法函数 4.判断是否回文 5.输出函数 6.主函数
//注意结构体中包含下标d[] 0下标为最后一位,长度len 还要初始
#include <iostream>
#include<cstring>
#include<algorithm>//reverse函数
using namespace std;
struct bign{
int d[1011];//大整数不是字符
int len;
bign(){
memset(d,0,sizeof(d));
len=0;
}
};
//将整数转换为bign
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';//d[i]中0位下标是最后一位
}
return a;
}
//定义加法
bign add(bign a,bign b){
bign c;
int carry=0;//进位
for(int i=0;i<a.len || i<b.len;i++){
c.d[c.len++]=(a.d[i]+b.d[i]+carry)%10;
carry=(a.d[i]+b.d[i]+carry)/10;
}
//此时len已经加到最高位了
if(carry!=0){
c.d[c.len++]=carry;//? 最高位在前进一位?
}
return c;
}
//判断是否为回文
bool judge(bign a){
for(int i=0;i<=a.len/2;i++){
if(a.d[i]!=a.d[a.len-i-1]){
return false;
}
}
return true;
}
//定义输出函数
void print(bign a){
for(int i=a.len-1;i>=0;i--){
printf("%d",a.d[i]);
}
cout<<endl;
}
int main(){
char n[1011];
int k,count=0;//k为操作上限,count为次数
scanf("%s%d",&n,&k);
bign a=change(n);
while(count<k &&judge(a)==false){//该过程已经能够判断judge(a)==true的情况了
bign b=a;
reverse(b.d,b.d+b.len);
a=add(a,b);
count++;
}
print(a);//print函数中定义了换行
printf("%d\n",count);
return 0;
}