Welcome to Subscribe On Youtube
3783. Mirror Distance of an Integer
Description
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) = 01which 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 <= 109
Solutions
Solution 1: Simulation
We define a function $\text{reverse}(x)$ to reverse the digits of integer $x$. Specifically, we initialize a variable $y$ to $0$, then repeatedly append the last digit of $x$ to the end of $y$, and remove the last digit from $x$, until $x$ becomes $0$. Finally, $y$ is the reversed integer.
Next, we compute the mirror distance of integer $n$, which is $\text{abs}(n - \text{reverse}(n))$, and return the result.
The time complexity is $O(\log n)$ and the space complexity is $O(1)$, where $n$ is the size of the input integer.
-
class Solution { public int mirrorDistance(int n) { return Math.abs(n - reverse(n)); } private int reverse(int x) { int y = 0; for (; x > 0; x /= 10) { y = y * 10 + x % 10; } return y; } } -
class Solution { public: int mirrorDistance(int n) { auto reverse = [](int x) -> int { int y = 0; for (; x; x /= 10) { y = y * 10 + x % 10; } return y; }; return abs(n - reverse(n)); } }; -
class Solution: def mirrorDistance(self, n: int) -> int: return abs(n - int(str(n)[::-1])) -
func mirrorDistance(n int) int { reverse := func(x int) int { y := 0 for ; x > 0; x /= 10 { y = y*10 + x%10 } return y } return abs(n - reverse(n)) } func abs(x int) int { if x < 0 { return -x } return x } -
function mirrorDistance(n: number): number { const reverse = (x: number): number => { let y = 0; for (; x > 0; x = Math.floor(x / 10)) { y = y * 10 + (x % 10); } return y; }; return Math.abs(n - reverse(n)); }