-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFindtheClosestPalindrome_564.cpp
147 lines (115 loc) · 2.65 KB
/
FindtheClosestPalindrome_564.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/*
~ Author : https://leetcode.com/tridib_2003/
~ Problem : 564. Find the Closest Palindrome
~ Link : https://leetcode.com/problems/find-the-closest-palindrome/
*/
/*
Intuition:
I) Find the palindrome just less than n
II) Find the palindrome just greater than n
III) Return the palindrome having min. difference with n
*/
class Solution {
public:
string roundUpNext(string s, int n) {
int i = n / 2;
while (i >= 0) {
if (s[i] != '9')
break;
--i;
}
if (i < 0) {
s = "1" + string (n, '0');
}
else {
++s[i];
for (int j = i + 1; j < n; ++j)
s[j] = '0';
}
int j = s.size() - 1; i = 0;
while (i < j) {
s[j--] = s[i++];
}
return s;
}
string roundUpPrev(string s, int n) {
int i = n / 2;
while (i >= 0) {
if (s[i] != '0')
break;
--i;
}
if (i == 0 && s[i] == '1')
return string (n - 1, '9');
--s[i];
for (int j = i + 1; j < n; ++j)
s[j] = '9';
int j = s.size() - 1; i = 0;
while (i < j) {
s[j--] = s[i++];
}
return s;
}
string generateNextPalindrome(string s) {
int m = s.size();
string t = s;
int i = 0, j = m - 1;
while (i < j) {
t[j--] = t[i++];
}
if (t > s)
return t;
if (m & 1) {
if (t[m / 2] == '9')
t = roundUpNext(t, m);
else
++t[m / 2];
}
else {
if (t[m / 2] == '9')
t = roundUpNext(t, m);
else {
++t[m / 2];
++t[m / 2 - 1];
}
}
return t;
}
string generatePrevPalindrome(string s) {
if (s == "11")
return "9";
int m = s.size();
string t = s;
int i = 0, j = m - 1;
while (i < j) {
t[j--] = t[i++];
}
if (t < s)
return t;
if (m & 1) {
if (t[m / 2] == '0')
t = roundUpPrev(t, m);
else
--t[m / 2];
}
else {
if (s[m / 2] == '0')
t = roundUpPrev(s, m);
else {
--t[m / 2];
--t[m / 2 - 1];
}
}
return t;
}
string nearestPalindromic(string n) {
string next = generateNextPalindrome(n);
string prev = generatePrevPalindrome(n);
long long num = stoll(n);
long long next_pal = stoll(next);
long long prev_pal = stoll(prev);
long long diff1 = num - prev_pal;
long long diff2 = next_pal - num;
return ((diff2 < diff1) ? next : prev);
}
};