Nearest Palindromic Number

You are given a string n representing a positive integer.

Return the closest palindromic integer to n, excluding n itself.

If there are multiple answers with the same absolute difference, return the smaller one.

A palindromic integer is a number that reads the same forward and backward.

Notes:

  • The returned value should be a string.
  • The input number itself cannot be chosen, even if it is already a palindrome.
  • The closest palindrome is the one with the minimum absolute difference from n.

Example 1:

Input: n = "808"

Output: "818"

Explanation:

The nearest palindromes around 808 are 797 and 818.

Their absolute differences are:

  • |808 - 797| = 11
  • |818 - 808| = 10

So, the closest palindrome is 818.

Example 2:

Input: n = "1000"

Output: "999"

Explanation:

The nearest palindromes around 1000 are 999 and 1001.

Their absolute differences are:

  • |1000 - 999| = 1
  • |1001 - 1000| = 1

Both are equally close, so we return the smaller one, which is 999.

Now Your Turn!

Pick the correct output for the given input

Input: n = "191"

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n.length <= 18
  • n consists only of digits '0' to '9'
  • n does not contain leading zeros
  • n represents an integer in the range [1, 1018 - 1]

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
string nearestPalindromic(string n) {
// Your code goes here
}
};
Test Case

Input:

N