Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Reading an integer's digits from right to left constructs its mirror value. The requested distance is then the absolute difference between that reversal and the original number, so preserve the original before consuming its digits.
Approach
Save the original value and initialize the reversal to zero. While digits remain, take the last digit with remainder modulo ten, append it to the reversal by multiplying the reversal by ten and adding the digit, and remove it from the working number with integer division by ten.
Return the absolute difference between the saved original and the reversal. Trailing zeros in the original become leading zeros in the reversed digit order and naturally disappear in integer arithmetic. A palindrome produces distance zero, and the absolute value handles either number being larger.
class Solution:
def mirrorDistance(self, n: int) -> int:
num = n
r = 0
while n:
r = r * 10 + (n % 10)
n //= 10
return abs(num - r)Complexity analysis
Let d be the decimal digit count. Time: O(d). Auxiliary space: O(1).
