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.
1 2 3 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 | |