-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
68 lines (60 loc) · 1.5 KB
/
Copy pathsolution.cpp
File metadata and controls
68 lines (60 loc) · 1.5 KB
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
class Solution
{
public:
vector<int> nextPalindrome(vector<int> &num)
{
int n = num.size();
// Case 1: If all digits are 9, answer is 100...001
bool allNine = true;
for (int x : num)
{
if (x != 9)
{
allNine = false;
break;
}
}
if (allNine)
{
vector<int> ans(n + 1, 0);
ans[0] = 1;
ans[n] = 1;
return ans;
}
// Step 1: Check whether left side is smaller than right side
int i = (n - 1) / 2;
int j = n / 2;
while (i >= 0 && num[i] == num[j])
{
i--;
j++;
}
bool leftSmaller = (i < 0 || num[i] < num[j]);
// Step 2: Mirror left half to right half
i = (n - 1) / 2;
j = n / 2;
while (i >= 0)
{
num[j] = num[i];
i--;
j++;
}
// Step 3: If left side was smaller, add 1 to the middle and handle carry
if (leftSmaller)
{
int carry = 1;
i = (n - 1) / 2;
j = n / 2;
while (i >= 0 && carry)
{
int val = num[i] + carry;
num[i] = val % 10;
carry = val / 10;
num[j] = num[i];
i--;
j++;
}
}
return num;
}
};