All problems
0472HardMathString

Nearest Mirror Reading on the Counter

Tracked in this browser only
Write code

Trains the technique from

LeetCode 564Find the Closest Palindrome

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A mechanical counter on a bottling line shows a whole number as the decimal string reading, with no leading zeros. The line's engineer likes a mirror reading: one whose digits are the same read left to right as right to left.

Find the mirror reading closest to reading, where closeness is the plain difference between the two numbers and the current reading itself does not count even when it already mirrors itself. When one mirror reading sits the same distance below as another sits above, take the smaller of the two.

Return the answer as a decimal string with no leading zeros. "0" counts as a mirror reading and is a possible answer.

Examples

Example 1

Input
reading = "88"
Output
"77"

77 lies 11 below the counter and 99 lies 11 above it, so the equal-distance rule picks 77.

Example 2

Input
reading = "6000"
Output
"5995"

5995 is 5 below the counter while 6006 is 6 above it, so 5995 is the answer.

Example 3

Input
reading = "5445"
Output
"5335"

The counter already mirrors itself but is barred from being its own answer. Both 5335 and 5555 sit 110 away, and the smaller one is taken.

Constraints

  • 1 <= reading.length <= 18
  • reading consists of digits only.
  • reading has no leading zeros.
  • reading represents a whole number in the range [1, 10^18 - 1].
  • The returned string must have no leading zeros; "0" is permitted.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def nearest_mirror(reading: str) -> str:
Java
public String nearestMirror(String reading)
September 7
Apply