转战英文版Leetcode
题目描述:
java实现:
采用计算机中位运算的概念进行求解,下面是代码:
class Solution {
public int divide(int dividend, int divisor) {
if (dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;
if (Math.abs(divisor) == 1) {
if (divisor > 0) return dividend;
else return -dividend;
}
long l1 = Math.abs((long)dividend);
long l2 = Math.abs((long)divisor);
int sol = 0;
while(l1 >= l2){
long x = l2, y = 1;
while(l1 >= x){
l1-=x;
sol+=y;
y+=y;
x+=x;
}
}
if (dividend > 0 && divisor < 0 || dividend<0 && divisor>0) sol = -sol;
return sol;
}
}
运行结果是:
可以看出并不怎么好,下面给出当中一个比较好的结果,运行15ms
class Solution {
public int divide(int dividend, int divisor) {
if (dividend == Integer.MIN_VALUE && divisor == 1) return Integer.MIN_VALUE;
if (dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;
int sign = ((dividend >> 31) + (divisor >> 31)) % 2 == 0 ? 1 : -1;
int a = dividend < 0 ? dividend : -1 * dividend;
int b = divisor < 0 ? divisor : -1 * divisor;
return sign * helper(a, b);
}
private int helper(int dividend, int divisor){
// calculate the quotient between two negative value
if (dividend > divisor) return 0;
int count = 0;
while (count < 31 && divisor << count < 0 && divisor << count >= dividend) count++;
return (int) Math.pow(2, count - 1) + helper(dividend - (divisor << (count - 1)), divisor);
}
}
python实现: