Mirror Distance of an Integer Problem
#3783
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3783.
You are given an integer n.
Define its mirror distance as: abs(n - reverse(n)) where reverse(n) is the integer formed by reversing the digits of n.
Return an integer denoting the mirror distance of n.
abs(x) denotes the absolute value of x.
Example 1:
Input: n = 25
Output: 27
Explanation:
- reverse(25) = 52.
- Thus, the answer is abs(25 - 52) = 27.
Example 2:
Input: n = 10
Output: 9
Explanation:
- reverse(10) = 01 which is 1.
- Thus, the answer is abs(10 - 1) = 9.
Example 3:
Input: n = 7
Output: 0
Explanation:
- reverse(7) = 7.
- Thus, the answer is abs(7 - 7) = 0.
Constraints:
1 <= n <= 10^9
Solution
Approach: Simulation
Reverse the digits of n by peeling off the last digit with % 10 and appending it to a new number, repeating until n is used up. A trailing zero such as in 10 simply becomes a leading zero of the reversed number and disappears (reverse(10) = 1). The answer is abs(n - reverse(n)).
Complexity: O(log n) time and O(1) extra space.
class Solution:
def mirrorDistance(self, n: int) -> int:
return abs(n - int(str(n)[::-1]))