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 (≤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
小结
这个主要是字符串的加法,然后判断回文数,没啥难度,字符串加法与前一章稍稍有所改进,这个的适用性更强,可以更好的适配其他进制的加法。
错误
当发现得到的分数少几分的时候,多数都是边界问题,这次又是没考虑本身就是回文数的情况。下次应着重看一下边界情况,争取一遍跑通!
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string Add(string s1, string s2) {
int mid = 0;
string s3 = "";
for (int i = s1.size()-1; i >-1; i--)
{
int num = (s1[i] - '0') + (s2[i] - '0') + mid;
mid = num / 10;
num = num % 10;
s3 = to_string(num) + s3;
}
if (mid == 1)s3 = "1" + s3;
return s3;
}
bool isPal(string num) {
int siz = num.size();
for (int i = 0; i < siz; i++)
{
if (num[i] != num[siz - i - 1])return false;
}
return true;
}
int main() {
string N1, N2;
int num;
cin >> N1 >> num;
if (isPal(N1)) {
cout << N1 << "\n" << 0;
return 0;
}
N2 = N1;
reverse(N2.begin(), N2.end());
for (int i = 0; i < num; i++)
{
N2 = N1;
reverse(N2.begin(), N2.end());
N1 = Add(N1, N2);
if (isPal(N1)) {
cout << N1<<"\n" << i+1;
return 0;
}
}
cout << N1 << "\n" << num;
return 0;
}