29. Divide Two Integers
Input: dividend = 10, divisor = 3
Output: 3Input: dividend = 7, divisor = -3
Output:-2Last updated
Was this helpful?
Input: dividend = 10, divisor = 3
Output: 3Input: dividend = 7, divisor = -3
Output:-2Last updated
Was this helpful?
Was this helpful?
class Solution {
public:
int divide(int dividend, int divisor) {
// 1. divisor = 0; 2. dividend = INT_MIN && divisor = -1
if(!divisor || dividend == INT_MIN && divisor == -1) return INT_MAX;
int sign = ((dividend < 0) ^ (divisor < 0))? -1: 1;
long long dvd = labs(dividend), dvs = labs(divisor);
int res = 0;
while(dvd >= dvs){
long long subtractor = dvs, multiplicand = 1;
while(dvd >= (subtractor << 1)){
subtractor <<= 1;
multiplicand <<= 1;
}
dvd -= subtractor;
res += multiplicand;
}
return sign == 1? res: -res;
}
};