#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool is_palindromic(string s)
{
int i = 0, j = s.length() - 1;
while (i < j)
{
if (s[i] != s[j])
return false;
i++;
j--;
}
return true;
}
string add_reverse(string s)
{
string res, rev = s;
int len = s.length();
reverse(rev.begin(), rev.end());
int carry = 0;
for (int i = len - 1; i >= 0; i--)
{
int tmp = s[i] - '0' + rev[i] - '0' + carry;
res += tmp % 10 + '0';
carry = tmp / 10;
}
if (carry == 1)
res += '1';
reverse(res.begin(), res.end());
return res;
}
int main()
{
string n;
int k;
cin >> n >> k;
int cnt = 0;
while (!is_palindromic(n) && cnt < k)
{
n = add_reverse(n);
cnt++;
}
cout << n << endl << cnt << endl;
return 0;
}这个题目用long long都拿不能全过,必须要用字符串。
PAT (Advanced) 1024. Palindromic Number (25)
最新推荐文章于 2020-05-09 20:56:33 发布
本文介绍了一个使用C++实现的算法,该算法通过不断将一个字符串与其反转后的字符串相加来试图构造一个回文数。文章提供的代码展示了如何判断一个字符串是否为回文数,并详细解释了当输入字符串不是回文数时如何通过特定步骤将其转换为回文数的过程。
2826

被折叠的 条评论
为什么被折叠?



