题目大意:判断一个不超过1000位的整数能否在10步内通过加上自身的反转数变成回文数,并输出计算过程。与PAT A1024 Palindromic Number 几乎是同一个问题,不过PAT A1024我用的是vector<int>来存储,用string存储好像也很方便。代码与PAT A1024也几乎一样。
AC代码:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
using namespace std;
bool isPalindromic(string &str)
{
for (int i = 0; i <= str.size() / 2; ++i)
{
if(str[i] != str[str.size() - 1 - i]) return false;
}
return true;
}
void iterate(string &str)
{
string rev = str;
reverse(rev.begin(), rev.end());
int carry = 0;
string sum;
for (int i = 0; i < str.size(); ++i)
{
int tmp = str[i] - '0' + rev[i] - '0' + carry;
if(tmp < 10)
{
sum += tmp + '0';
carry = 0;
}
else
{
sum += tmp - 10 + '0';
carry = 1;
}
}
if(carry) sum += '1';
reverse(sum.begin(), sum.end());
printf("%s + %s = %s\n", str.c_str(), rev.c_str(), sum.c_str());
str = sum;
}
int main()
{
string str;
cin >> str;
int K = 0;
while(K < 10 && !isPalindromic(str))
{
iterate(str);
K++;
}
if(isPalindromic(str)) printf("%s is a palindromic number.", str.c_str());
else printf("Not found in 10 iterations.");
return 0;
}