// Reverse and Add UVA - 10018.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
/*
https://vjudge.net/problem/UVA-10018#author=md_bayazid
The “reverse and add” method is simple: choose a number, reverse its digits and add it to the original. If the sum is not a palindrome
(which means, it is not the same number from left to right and right to left), repeat this procedure.
195 Initial number
591
---
786
687
---
1473 (For example)
3741
----
5214
4125
----
9339 (Resulting Palindrome)
In this particular case the palindrome ‘9339’ appeared after the 4th addition.
This method leads to palindromes in a few steps for almost all of the integers.
But there are interesting exceptions. 196 is the first number for which no palindrome has been found.
It is not proven though, that there is no such a palindrome.
You must write a program that give the resulting palindrome and the number of iterations (addi tions) to compute the palindrome.
You might assume that all tests data on this problem:
• will have an answer ,
• will be computable with less than 1000 iterations (additions),
• will yield a palindrome that is not greater than 4,294,967,295.
Input
The first line will have a number N (0 < N ≤ 100) with the number of test cases, the next N lines will have a number P to compute its palindrome.
Output
For each of the N tests, you will have to write a line with the following data: minimum number of iterations and the resulting palindrome
itself separated by one space.
Sample Input
3
195
265
750
Sample Output
4 9339
5 45254
3 6666
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int T;
vector<int> a, b;
void fill(long long u, vector<int>& a) {
if (u == 0) { a.push_back(0); return; }
a.clear();
while (u) {
a.push_back(u % 10);
u /= 10;
}
}
bool check(vector<int> a) {
int l = 0; int r = a.size() - 1;
while (l < r) {
if (a[l] != a[r]) return false;
l++; r--;
}
return true;
}
vector<int> add(const vector<int>& a, const vector<int>& b) {
int len = min(a.size(), b.size());
int carry = 0;
vector<int> ret;
for (int i = 0; i < len; i++) {
ret.push_back((a[i] + b[i] + carry) % 10);
carry = (a[i] + b[i] + carry) / 10;
}
if (carry) ret.push_back(carry);
return ret;
}
void solve() {
int ans = 0;
while (false==check(a)) {
a = add(a, b);
b= a; reverse(b.begin(), b.end());
ans++;
}
cout << ans << " ";
for (int i = a.size() - 1; i >= 0; i--) {
cout << a[i];
}
cout << endl;
return;
}
int main()
{
cin >> T;
while (T--) {
long long u;
cin >> u;
fill(u, a);
b = a; reverse(b.begin(), b.end());
solve();
}
return 0;
}
标签:palindrome,int,number,will,Add,vector,carry,UVA,10018
From: https://www.cnblogs.com/itdef/p/18546669