Leetcode#29 Divide Two Integers
Published:
Link:
https://leetcode.com/problems/divide-two-integers/description/
Idea:
Left shift == “2*divisor”; Find out biggest possible left shift number.
Solution:
class Solution {
public:
int divide(int dividend, int divisor) {
if (divisor == 0)
return dividend >= 0 ? INT_MAX : INT_MIN;
if (dividend == INT_MIN && divisor == -1)
return INT_MAX;
bool neg = false;
if((dividend<0 && divisor>0) || (dividend>0 && divisor<0))
neg = true;
unsigned long long a_dividend = abs((long long)dividend);
unsigned long long a_divisor = abs((long long)divisor);
int i = 0;
while(a_divisor << i < a_dividend)
i++;
int res = 0;
while (a_divisor <= a_dividend) {
if (a_dividend >= a_divisor << i) {
res += 1<<i;
a_dividend -= a_divisor << i;
}
i--;
}
return neg ? 0-res : res;
}
};