Mirror Distance of an Integer LeetCode Solution

🚀 Day 31/40 – DSA Challenge 📌 LeetCode Problem – Mirror Distance of an Integer 📝 Problem Statement Given an integer n, compute its mirror distance: | n - reverse(n) | Where reverse(n) is formed by reversing the digits of n. 📌 Example Input: n = 25 Output: 27 Explanation: reverse(25) = 52 |25 - 52| = 27 💡 Key Insight The main task is correctly reversing the number. 👉 Extract digits one by one 👉 Build the reversed number ⚠️ Important: Do not lose the original value of n while reversing. 🚀 Algorithm 1️⃣ Store original value 2️⃣ Reverse the number using modulo and division 3️⃣ Return absolute difference ✅ Java Code (Correct & Safe) class Solution { public int mirrorDistance(int n) { int original = n; int reversed = 0; while (n != 0) { int digit = n % 10; reversed = reversed * 10 + digit; n /= 10; } return Math.abs(original - reversed); } } ⏱ Complexity Time Complexity: O(d) (d = number of digits) Space Complexity: O(1) ⚠️ Common Mistake (You Had This Earlier) return Math.abs(n - reversed); ❌ 👉 Because n becomes 0 after the loop ✔ Fix: return Math.abs(original - reversed); ✅ 📚 Key Learnings – Day 31 ✔ Preserve original values during transformations ✔ Digit extraction using % and / is fundamental ✔ Small mistakes can break correct logic ✔ Always dry run with simple inputs Simple problem. Careful implementation. Bug fixed, concept clear. Day 31 completed. Consistency continues 💪🔥 #180DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #Math #LeetCode

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories