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
This code calculates the mirror distance between a number and its digit-reversed counterpart. The mirrorDistance function takes a number n, reverses its digits using the helper function reverse, and then returns the absolute difference between the original and reversed numbers. The reverse function works by repeatedly extracting the last digit of the number using the modulo operator (n % 10), shifting the result left by multiplying by 10, and removing the processed digit with Math.floor(n / 10) until all digits are extracted and reassembled in reverse order. For example, with n = 123, the reverse function produces 321, and mirrorDistance returns Math.abs(123 - 321) = 198.
/**
* @param {number} n
* @return {number}
*/
var mirrorDistance = function(n) {
return Math.abs(n - reverse(n));
};
const reverse = (n) => {
let res = 0;
while (n > 0) {
res = res * 10 + (n % 10);
n = Math.floor(n / 10);
}
return res;
};