topic
Given a k+1k+1k+1-bit positive integer NNN, write it as ak...a1a0a_k \cdots a_1 a_0ak...a1a0, where 0≤ai for all iii <100 \le a_i <100≤ai<10 and ak>0a_k> 0ak>0. NN is called a palindrome number , if and only if ai=ak−ia_i = a_{ki}ai=ak−i for all iii. Zero is also defined as a palindrome number.
The number of non-palindromes can also be transformed into the number of palindromes through a series of operations. First reverse the number, and then add the reversal number to the number. If the sum is not a palindrome number, repeat the reversal and then add operation until a palindrome number appears. If a non-palindromic number can be transformed into a palindromic number, this number is called the delayed palindrome number . (The definition is translated from https://en.wikipedia.org/wiki/Palindromic_number )
Given any positive integer, this question requires you to find the palindrome number that it changes.
Input format:
Enter a positive integer with no more than 1000 digits in one line.
Output format:
For a given integer, output the process of changing the number of palindrome line by line. The format of each line is as follows
A + B = C
Which A
is the original number, B
is A
the number of reversal C
is their sum. A
Start with the integer entered. Repeat until C
becomes palindrome within 10 steps, in this case the output line C is a palindromic number.
; the step 10, or if failed to get palindrome, the final outputs in a row Not found in 10 iterations.
.
Input example 1:
97152
Output sample 1:
97152 + 25179 = 122331
122331 + 133221 = 255552
255552 is a palindromic number.
Input example 2:
196
Output sample 2:
196 + 691 = 887
887 + 788 = 1675
1675 + 5761 = 7436
7436 + 6347 = 13783
13783 + 38731 = 52514
52514 + 41525 = 94039
94039 + 93049 = 187088
187088 + 880781 = 1067869
1067869 + 9687601 = 10755470
10755470 + 07455701 = 18211171
Not found in 10 iterations.
Thinking analysis:
Note that the return value of reverse is void, so you have to write a new function. Pay attention to carry when adding.
Code:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
string rev(string s){
reverse(s.begin(), s.end());
return s;
}
string add(string s1, string s2){
string s = s1;
int cnt = 0;
for(int i = s.size() - 1; i >= 0; i--){
s[i] = (s1[i] + s2[i] - 96 + cnt) % 10 + 48;
cnt = (s1[i] + s2[i] - 96 + cnt) / 10;
}
if(cnt > 0) s = "1" + s;
return s;
}
int main(){
string s;
cin >> s;
string sum = s;
for(int i = 0; i < 10; i++){
if(sum == rev(sum)){
cout << sum << " is a palindromic number." << endl;
return 0;
}
s = sum;
sum = add(s, rev(sum));
cout << s << " + " << rev(s) << " = " << sum << endl;
}
cout << "Not found in 10 iterations." << endl;
return 0;
}