题目大意:判断一个不超过10^10的数N,能否在K步内通过加上自身的反转数变成回文数。
与A1023 Have fun with Numbers 相同,依然是大数加法,用vector<int>存储并按照要求反转相加,判断回文即可。
坑点在于开始的输入时,N 要设置成long long型,设置成 int 型会溢出导致测试点7和8运行超时。
AC代码如下:
#include <iostream>
#include <vector>
#include <cstdio>
using namespace std;
bool isPalindromic(vector<int> &v)
{
for (int i = 0; i <= v.size() / 2; ++i)
{
if(v[i] != v[v.size() - 1 - i]) return false;
}
return true;
}
void addReverse(vector<int> &v)
{
vector<int> ans;
int carry = 0;
for (int i = 0; i < v.size(); ++i)
{
int tmp = v[i] + v[v.size() - 1 - i] + carry;
if(tmp >= 10)
{
ans.push_back(tmp - 10);
carry = 1;
}
else
{
ans.push_back(tmp);
carry = 0;
}
}
if(carry == 1) ans.push_back(1);
v = ans;
}
int main()
{
long long N, K;
cin >> N >> K;
vector<int> v;
while(N > 0)
{
v.push_back(N % 10);
N /= 10;
}
int step = 0;
while(step < K && !isPalindromic(v))
{
addReverse(v);
step++;
}
for (int i = v.size() - 1; i >= 0; --i)
{
printf("%d", v[i]);
if(i == 0) printf("\n");
}
printf("%d", step);
return 0;
}