Skip to content

Commit 6390dce

Browse files
committed
PALIN - The Next Palindrome
1 parent dbdd028 commit 6390dce

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

SPOJ/PALIN.cpp

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/* @amitbansal7 */
2+
#include<bits/stdc++.h>
3+
using namespace std;
4+
5+
string inc(string left) {
6+
7+
int idx = left.size() - 1;
8+
9+
while (left[idx] == '9') {
10+
left[idx] = '0';
11+
idx--;
12+
}
13+
14+
left[idx] = left[idx] + 1;
15+
return left;
16+
}
17+
18+
int main() {
19+
int n;
20+
cin >> n;
21+
22+
while (n--) {
23+
string s;
24+
cin >> s;
25+
26+
int len = s.size();
27+
bool isOdd = len % 2;
28+
29+
char center = '\0';
30+
if (isOdd) center = s[len / 2];
31+
32+
string left = s.substr(0, len / 2);
33+
string right = left;
34+
reverse(right.begin(), right.end());
35+
36+
string pal = left + center + right;
37+
if (center == '\0')
38+
pal = left + right;
39+
bool res = 0;
40+
if (pal > s) {
41+
cout << pal << endl;
42+
}
43+
else {
44+
if (center != '\0') {
45+
if (center < '9') {
46+
center = center + 1;
47+
cout << left + center + right << endl;
48+
res = 1;
49+
}
50+
else {
51+
center = '0';
52+
}
53+
}
54+
if (res) continue;
55+
56+
string tLeft;
57+
for (int i = 0; i < left.size(); i++)
58+
tLeft += '9';
59+
60+
if (left == tLeft) {
61+
string res = "1";
62+
for (int i = 0; i < len - 1; i++)
63+
res += '0';
64+
res += "1";
65+
cout << res << endl;
66+
} else {
67+
left = inc(left);
68+
right = left;
69+
reverse(right.begin(), right.end());
70+
71+
if (center == '\0')
72+
cout << left + right << endl;
73+
else
74+
cout << left + center + right << endl;
75+
}
76+
}
77+
}
78+
}

0 commit comments

Comments
 (0)