Divide Two Integers Without Multiplication or Division

🚀 Day 22/40 – DSA Challenge 📌 LeetCode Problem – Divide Two Integers 📝 Problem Statement Given two integers dividend and divisor, divide them without using multiplication, division, or mod operator. Return the quotient after dividing. 📌 Example Input: dividend = 10 divisor = 3 Output: 3 📌 Edge Case Input: dividend = -2147483648 divisor = -1 Output: 2147483647 (Integer.MAX_VALUE) 💡 Key Insight We simulate division using bit shifting (doubling). 👉 Instead of subtracting one by one 👉 Subtract largest possible multiples using powers of 2 🔥 Optimized Approach – Bit Manipulation 🧠 Idea Convert numbers to long (avoid overflow) Work with absolute values Keep doubling divisor using: temp << 1 Subtract largest chunk each time 🚀 Algorithm 1️⃣ Handle overflow case 2️⃣ Convert to long and take absolute values 3️⃣ While dividend ≥ divisor: Keep doubling divisor Subtract largest possible multiple Add to result 4️⃣ Apply sign ✅ Java Code (Optimal O(log n)) class Solution { public int divide(int dividend, int divisor) { if (dividend == Integer.MIN_VALUE && divisor == -1) { return Integer.MAX_VALUE; } long dvd = Math.abs((long) dividend); long dvs = Math.abs((long) divisor); int result = 0; while (dvd >= dvs) { long temp = dvs; int multiple = 1; while (dvd >= (temp << 1)) { temp <<= 1; multiple <<= 1; } dvd -= temp; result += multiple; } if ((dividend < 0) ^ (divisor < 0)) { result = -result; } return result; } } ⏱ Complexity Time Complexity: O(log n) Space Complexity: O(1) 📚 Key Learnings – Day 22 ✔ Bit manipulation can replace division ✔ Doubling strategy reduces time drastically ✔ Handle overflow carefully ✔ Use long to avoid integer issues Classic problem. Bit-level thinking. Edge cases mastered. Day 22 completed. Consistency continues 💪🔥 #180DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #BitManipulation #LeetCode

  • graphical user interface, text, application, chat or text message

To view or add a comment, sign in

Explore content categories