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.
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 3
Sample Output 1:
484
2
Sample Input 2:
69 3
Sample Output 2:
1353
3
题目大意:
给定一个大整数(超过十位的),如果他不是回文串(即从前往后与从后往前均为同一数字),则进行如下操作:第一步将得到的数字反过来,第二步将两个数字相加。直至为回文串为止。
现给定一个数字与最大的操作步骤,无论是否为回文串均要输出结果与操作的步数。
思路:
大整数用string 处理,方便输入。输入后从后往前处理,设置进位step,进行相应的进位计算。最终将字符串重新反转便得到输出结果。
参考代码:
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int step, cnt;
string s1, s2, ans;
int main(){
cin >> s1 >> step;
ans = s2 = s1;
reverse(s1.begin(), s1.end());
while(cnt < step && s2 != s1){
int temp = 0;
ans.clear();
for(int i = s1.size() - 1; i >= 0; --i){
temp = s1[i] - '0' + s2[i] - '0' + temp;
ans += temp % 10 +'0';
temp /= 10;
}
if(temp) ans += temp + '0';
s2 = s1 = ans;
reverse(s1.begin(), s1.end());
cnt++;
}
reverse(ans.begin(), ans.end());
cout << ans << endl << cnt;
return 0;
}