FastPrepNearest Palindromic Number

Nearest Palindromic Number

Apple logoApple● HardFULLTIMEONSITE INTERVIEW
Learn

Problem statement

The decimal string number represents a positive integer without leading zeroes. Return the decimal representation of the closest nonnegative palindromic integer different from that integer.

Distance is the absolute numeric difference. If two palindromes are equally close, return the smaller one. The returned representation has no leading zeroes, except that zero is written "0".

Function

nearestPalindrome(number: String) → String

Examples

Example 1

number = "121"return = "111"

The input itself is excluded. Both 111 and 131 are ten away, so the smaller 111 wins, as in the source example.

Example 2

number = "123"return = "121"

Mirroring the leading half gives the nearest different palindrome.

Example 3

number = "1"return = "0"

Zero and two are equally close, so zero wins.

Constraints

  • 1 <= number.length <= 18.
  • The input contains decimal digits only and represents a positive integer.

More Apple problems

See Apple hiring insights
public String nearestPalindrome(String number) {
    // Write your solution here.
}
number"121"
expected"111"
Checking account…