In my code,I use two char arrays to store the inpuet number and temporary results (like number’s reverse and the sum).
- bool isPali(char * N): judge if N is a palindromic
- void op(char N1,char N2):store the reverse of N1 and its reverse’s sum in N2(that’s why I used reverse fuction again after op in main())
- *void reverse(char *N1,char N2):put the N1’s reverse into N2
#include <iostream>
#include <stdio.h>
#include<stdlib.h>
#include <math.h>
#include <algorithm>
#include <vector>
#include <map>
#include <string.h>
#include<stack>
#include <unordered_map>
#include <set>
using namespace std;
const int MAXN = 1100;
char N1[MAXN];
char N2[MAXN];
bool isPali(char * N)
{
for (int i = 0; i <= strlen(N) / 2 + 1; i++)
{
if (N[i] != N[strlen(N) -1 - i]) return false;
}
return true;
}
void op(char *N1,char* N2)
{
for (int i = strlen(N1) - 1; i >= 0; i--)
{
int ii = strlen(N1) - 1 - i;
int s = N1[i] - '0' + N1[ii] - '0';
if (i == strlen(N1) - 1)
{
N2[ii] = s % 10 + '0';
N2[ii + 1] = s / 10 + '0';
}
else {
int a = N2[ii] - '0' + s;
N2[ii] = a % 10 + '0';
if (i != 0) N2[ii + 1] = a / 10 + '0';
else if (a / 10 > 0) N2[ii + 1] = a / 10 + '0';
}
}
}
void reverse(char *N1,char *N2)
{
for (int j = 0; j < strlen(N1); j++)
{
N2[strlen(N1) - 1 - j] = N1[j];
}
}
int main() {
cin >> N1;
if (isPali(N1)) cout << N1 << " is a palindromic number." << endl;
else {
int i = 0;
for (i; i < 10; i++)
{
cout << N1 << " + ";
reverse(N1, N2);
cout << N2 << " = ";
reverse(N2, N1);
op(N1, N2);
reverse(N2, N1);
cout << N1 << endl;
if (isPali(N1)) {
cout << N1 << " is a palindromic number." << endl;
break;
}
}
if (i == 10) cout << "Not found in 10 iterations." << endl;
}
return 0;
}