原题连接:https://www.patest.cn/contests/pat-a-practise/1024
题目如下:
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 (<= 1010) is the initial numer and K (<= 100) 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 3Sample Output 1:
484 2Sample Input 2:
69 3Sample Output 2:
1353 3
这道题和上一道题很相似,这道题是模拟加法,只不过先得反转,并且还得判断是否为回文。
我之前一直在用C语言写,这次尝试用了C++中的vector。注意可以使用.clear()删除数据,可以使用=将一个vector赋给另一个。
1 #include<stdio.h> 2 #include<iostream> 3 #include<vector> 4 #include<string.h> 5 using namespace std; 6 7 int IsPalindromic(vector<int>&P) 8 { 9 int i,flag=1,j; 10 j=P.size()-1; 11 for (i=0;i<P.size()/2;i++) 12 { 13 if(P[i]!=P[j-i]) 14 { 15 flag=0; 16 break; 17 } 18 } 19 return flag; 20 } 21 int main() 22 { 23 char src[15]; 24 scanf("%s",&src); 25 vector<int>sum,tmp; 26 int i=strlen(src)-1,t,j,k,s; 27 for (;i>=0;i--) 28 { 29 t=src[i]-'0'; 30 sum.push_back(t); 31 } 32 int step; 33 scanf("%d",&step); 34 int r,p=0; 35 for (i=0;i<step;i++) 36 { 37 if (IsPalindromic(sum))break; 38 else 39 { 40 k=sum.size()-1; 41 for (j=0;j<sum.size();j++) 42 { 43 s=sum[j]+sum[k-j]+p; 44 r=s%10; 45 p=s/10; 46 tmp.push_back(r); 47 } 48 if (p!=0)tmp.push_back(p); 49 p=0; 50 sum.clear(); 51 sum=tmp; 52 tmp.clear(); 53 } 54 } 55 if (i<=step) 56 { 57 for (j=sum.size()-1;j>=0;j--)printf("%d",sum[j]); 58 printf(" "); 59 printf("%d ",i); 60 } 61 else 62 { 63 for (j=sum.size()-1;j>=0;j--)printf("%d",sum[j]); 64 printf(" "); 65 printf("%d ",step); 66 } 67 return 0; 68 }