题目链接:https://www.patest.cn/contests/pat-a-practise/1024
题意:给一个数字,不断加上这个数字所有位反过来的数字,最多k次,问第几次能变成回文串。
会爆long long 。用字符串来做就好。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
bool check(string n) {
for(int i = 0; i < n.size()/2; i++) {
if(n[i] != n[n.size() - i - 1]) return 0;
}
return 1;
}
int main() {
string n;
int k;
cin >> n >> k;
int i;
string tmp;
for(i = 0; i < k; i++) {
if(check(n)) break;
tmp = n;
reverse(tmp.begin(), tmp.end());
int carry = 0;
string res;
for(int j = n.size()-1; j >= 0; j--) {
int tt = n[j] - '0' + tmp[j] - '0' + carry;
carry = tt / 10;
res.insert(res.begin(), tt%10 + '0');
}
if(carry) res.insert(res.begin(), carry + '0');
n = res;
}
cout << n << endl;
cout << i << endl;
return 0;
}
本文介绍了一道编程题的解决方案,题目要求通过不断将一个数字与其反转后的数字相加,直到得到一个回文数为止,并记录达到回文数所需的次数。文章提供了一个使用C++实现的具体代码示例,该示例通过字符串操作来避免数值运算可能产生的溢出问题。
2859

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



