mirror of
https://github.com/Manoj-HV30/dsa-competitive-programming.git
synced 2026-05-16 19:35:22 +00:00
29 lines
1.5 KiB
C++
29 lines
1.5 KiB
C++
class Solution{
|
|
public:
|
|
int divide(int dividend, int divisor){
|
|
if(divisor == 1) return dividend;
|
|
if(divisor == -1) return dividend == INT_MIN ? INT_MAX : -dividend;
|
|
|
|
bool isPositive = (dividend > 0) == (divisor > 0);
|
|
|
|
int a = dividend > 0? -dividend : dividend;
|
|
int b = divisor > 0? -divisor : divisor;
|
|
|
|
int ans =0;
|
|
while(a<=b){
|
|
int temp = b, multiple = 1;
|
|
while(temp>= INT_MIN>>1 && a< (temp<<1)){
|
|
temp<<=1;
|
|
multiple <<= 1;
|
|
|
|
}
|
|
a-= temp;
|
|
ans+=multiple;
|
|
}
|
|
return isPositive? ans: -ans;
|
|
|
|
|
|
}
|
|
};
|
|
/*This solution performs integer division without using *, /, or % by simulating binary long division. To avoid overflow—especially the undefined behavior of abs(INT_MIN)—it first converts both the dividend and divisor into negative numbers, because the negative range of a 32-bit signed integer is larger and can safely represent INT_MIN. The only true overflow case (INT_MIN / -1) is handled upfront by returning INT_MAX. The algorithm then repeatedly subtracts the largest possible power-of-two multiple of the divisor from the dividend using safe left shifts guarded against overflow, accumulating the corresponding multiple in the quotient. This guarantees correctness for all edge cases, runs in O(log^2 n) time with O(1) space, and keeps all intermediate operations within valid integer bounds.*\
|