题目:
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.
Input Specification:
Each input file contains one test case. Each case consists of two positive numbers N and K, where N (≤) is the initial numer and K (≤) is the maximum number of steps. The numbers are separated by a space.
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.
Sample Input 1:
67 3
Sample Output 1:
484
2
Sample Input 2:
69 3
Sample Output 2:
1353
3
分析:
回文数模拟题。long long最多19位,每一次操作都可能增加一位,最多操作100次,因此会溢出。此处使用字符串。
代码:
long long溢出的代码:有两组测试数据不能通过
1 #include<iostream> 2 using namespace std; 3 int k; 4 long long n; 5 long long getRev(long long n){ //获取逆序的数字 6 long long x=0; 7 while(n){ 8 x=x*10+n%10; 9 n/=10; 10 } 11 return x; 12 } 13 14 bool judgePal(long long n){ //判断是否为回文数 15 int x[20]; 16 int l=0; 17 while(n){ 18 x[l++]=n%10; 19 n/=10; 20 } 21 for(int i=0;i<l/2;i++){ 22 if(x[i]!=x[l-1-i]){ 23 return false; 24 } 25 } 26 return true; 27 } 28 29 30 int main(){ 31 cin>>n>>k; 32 for(int i=0;i<=k;i++){ 33 if(judgePal(n)||i==k){ 34 cout<<n<<endl<<i<<endl; 35 break; 36 }else{ 37 long long rev=getRev(n); 38 n+=rev; 39 } 40 } 41 return 0; 42 }
string代码:
1 #include<iostream> 2 #include<cstring> 3 using namespace std; 4 string n; 5 int k; 6 int x[120]; //字符串转换成数组 7 int bit; //数字位数 8 bool judgePal(){ //判断是否为回文数 9 for(int i=0;i<bit/2;i++){ 10 if(x[i]!=x[bit-1-i]){ 11 return false; 12 } 13 } 14 return true; 15 } 16 17 int main(){ 18 cin>>n>>k; 19 bit=n.length(); 20 for(int i=0;i<bit;i++){ //逆序存放 21 x[bit-1-i]=n[i]-'0'; 22 } 23 for(int i=0;i<=k;i++){ 24 if(judgePal()||i==k){ 25 for(int j=bit-1;j>=0;j--){ 26 cout<<x[j]; 27 } 28 cout<<endl<<i<<endl; 29 break; 30 }else{ 31 int xx[120]; //下面加法之前要备份一下,否则加数会随着循环进行变化 32 for(int j=0;j<120;j++){ 33 xx[j]=x[j]; 34 } 35 for(int j=0;j<bit;j++){ //加上逆序数 36 x[j]+=xx[bit-1-j]; 37 } 38 for(int j=0;j<bit;j++){ //大整数加法 39 if(x[j]>=10){ 40 x[j+1]++; 41 x[j]-=10; 42 } 43 } 44 for(int j=119;j>=0;j--){ //更新位数 45 if(x[j]!=0){ 46 bit=j+1; 47 break; 48 } 49 } 50 } 51 } 52 return 0; 53 }