247. Mirror Number
A museum labels its exhibits with numeric tickets, and a ticket is called a mirror number if its decimal digits read the same from left to right as from right to left. Given the integer x, return true when it is a mirror number and false otherwise.
Negative numbers are never mirror numbers because of the minus sign, and any positive number ending in 0 can only match if it begins with 0, so it fails too; 0 itself is a mirror number. For example 5115 and 9 qualify, while 340 and -77 do not.
Solve it without converting the integer to a string. Instead use arithmetic: it is enough to reverse only the second half of the digits and compare it with the first half, which also avoids any 32-bit overflow. Time complexity should be O(log x) and extra space O(1).
Example 1
- Input:
- x = 48384
- Output:
- true
- Explanation:
Digits 4-8-3-8-4 read the same from both ends, so 48384 is a mirror number.
Example 2
- Input:
- x = -232
- Output:
- false
- Explanation:
A leading minus sign never matches a trailing digit, so negative numbers are not mirror numbers.
Example 3
- Input:
- x = 1030
- Output:
- false
- Explanation:
Reversed it reads 0301, which is not the same number as 1030.
Constraints
-231 ≤ x ≤ 231 - 1
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(log x)
- Space
- O(1)