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 (≤10
10
) 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 3
Sample Output 1:
484
2
Sample Input 2:
69 3
Sample Output 2:
1353
3
题意
给你两个数n和k,让你看n是不是回文数,如果不是,就在k次以内运算,如果在k次运算之内算出回文就输出回文和当前计算次数;如果不能在k次以内运算出来,就输出第k次运算的结果和k。
运算是指样例给出67 3,67不是回文,那么进行一下计算:67 + 76 = 143, 143 + 341 = 484,484是回文就结束运算
#include<bits/stdc++.h>
using namespace std;
bool isPalin(string s){
int left=0,right=s.length()-1;
while(left<right){
if(s[left]!=s[right])
return false;
left++;
right--;
}
return true;
}
string add(string s){
int a[1000],b[1000],res[1000];
for(int i=s.length()-1;i>=0;i--)
b[s.length()-i-1]=s[i]-'0';
for(int i=0;i<s.length();i++)
a[i]=s[i]-'0';
memset(res,0,sizeof(res));
int len=s.length();
for(int i=0;i<s.length();i++){
res[i]+=a[i]+b[i];
if(res[i]>=10){
res[i+1]+=(res[i])/10;
res[i]%=10;
if(i==len-1)//进位
len++;
}
}
string ans;
for(int i=len-1;i>=0;i--)
ans+=res[i]+'0';
return ans;
}
int main(){
string s;
int k,cnt=0;
cin >> s >> k;
while(k--){
if(isPalin(s))
break;
cnt++;
s=add(s);
}
cout << s << endl << cnt;
}