PAT-A 1024. Palindromic Number

题目链接:https://www.patest.cn/contests/pat-a-practise/1024


题意:给一个数字,不断加上这个数字所有位反过来的数字,最多k次,问第几次能变成回文串。

会爆long long 。用字符串来做就好。


#include 
#include 
#include 
#include 
#include 
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;
}


你可能感兴趣的:(pat)