Divide two integers without using division or multiplication operators
Prashant Mishra
Posted on September 25, 2024
Tc :
Sc: O(1)
class Solution {
public int divide(int dividend, int divisor) {
//edges cases
if(dividend == divisor) return 1;
boolean positive = true;
if(dividend <=0 && divisor >0) positive = false;
else if(dividend >=0 && divisor <0) positive = false;
long n = dividend;
long d = divisor;
n = Math.abs(n);
d = Math.abs(d);
long quotient = 0;
while (n >= d) {
int count = 0;
while (n >= (d << (count + 1))) {
count++;
}
n -= (d << count);
quotient += (1 << count);
}
if(quotient == (1<<31) && positive) return Integer.MAX_VALUE;
else if(quotient ==(1<<31) && !positive) return Integer.MIN_VALUE;
return (int)( positive ? quotient: -quotient);
}
}
💖 💪 🙅 🚩
Prashant Mishra
Posted on September 25, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
githubcopilot AI Innovations at Microsoft Ignite 2024 What You Need to Know (Part 2)
November 29, 2024