For example:
195 Initial number
591
-----
786
687
-----
1473
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 step for almost all of the integers.But there are interesting exceptions. 196 is the first number for whichno palindrome has been found. It is not proven though, that there is nosuch a palindrome.
Task :
You must write a program that give the resulting palindrome and thenumber of iterations (additions) 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.
3 195 265 750
3 6666
#include <iostream> #include <cstdio> #include <cstring> #include <vector> using namespace std; bool palindrome_num(vector<int>bit) { if(bit.size() == 1|| bit.size() == 0)return true; if(bit[0] != bit[bit.size() - 1])return false; bit.erase(bit.begin()); bit.erase(bit.end() - 1); return palindrome_num(bit); } void reverse_add(vector<int>bit) { int step = 0; while(!palindrome_num(bit)) { step++; vector<int>sum; int carry = 0; for(int i = 0 , j = bit.size() - 1 ; i < bit.size() ; i ++ , j--) { int temp = bit[i] + bit[j] + carry; carry =((temp - 10 >= 0)? 1 : 0) ; sum.push_back(temp % 10); } if(carry)sum.push_back(carry); bit = sum; } cout << step << ' '; for(int i = bit.size() - 1 ; i >= 0 ; i--) { cout << bit[i]; } cout << endl; } int main() { int n; vector <int>bit; cin >> n; while(n --) { int a; cin >> a; bit.clear(); while(a) { bit.push_back(a % 10); a /= 10; } reverse_add(bit); } return 0; }