-
Notifications
You must be signed in to change notification settings - Fork 2
/
Next Smallest Palindrome
54 lines (51 loc) · 976 Bytes
/
Next Smallest Palindrome
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
#include <bits/stdc++.h>
using namespace std;
void largerpalindrome(int arr[], int n){
int mid = n/2;
int i = mid-1;
int j= n%2?mid+1:mid;
bool leftsmaller = false;
while(i>=0 && arr[i]==arr[j]){
i--;
j++;
}
if(i<0&&arr[i]<arr[j]){
leftsmaller = true;
}
while(i>=0){
arr[j++] =arr[i--];
}
if(leftsmaller == true){
int carry = 1;
i = mid-1;
if(n%2){
arr[mid]+=carry;
carry = arr[mid]/10;
arr[mid] %=10;
j = mid+1;
}
else{
j = mid;
}
while(i>=0){
arr[i]+=carry;
carry = arr[i]/10;
arr[i] %=10;
arr[j++] = arr[i--];
}
}
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
largerpalindrome(arr, n);
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
return 0;
}