Find the Closest Palindrome
Real-world version: Nearest Mirror Reading on the CounterThe statement here is our own: the same inputs, outputs and technique.
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 starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def nearest_mirror(reading: str) -> str:public String nearestMirror(String reading)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 14 test cases: 14 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's