Divide two integers without using multiplication, division and mod operator.
public class Solution {
public int divide(int dividend, int divisor) {
boolean neg = false;
long num1 = dividend;
long num2 = divisor;
if(num1<0) {
num1 = -num1;
neg = !neg;
}
if(num2<0) {
num2 = -num2;
neg = !neg;
}
ArrayList<Long> multip = new ArrayList<Long>();
long i= num2;
while(i<=num1 && i>0) {
multip.add(i);
i = i<<1;
}
long ret = 0;
for(int j=multip.size()-1;j>=0;j--) {
if(num1>=multip.get(j)) {
num1 -= multip.get(j);
ret += (long)1<<j;
}
}
if(neg) {
ret = -ret;
}
if (ret > Integer.MAX_VALUE) return Integer.MAX_VALUE;
return (int)ret;
}
}
============
public class Solution {
public int divide(int dividend, int divisor) {
if (divisor == 0) return Integer.MAX_VALUE;
if (dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;
long l1 = Math.abs((long) dividend);
long l2 = Math.abs((long) divisor);
if (l1 < l2) {
return 0;
}
int sign = 1;
if (dividend > 0 != divisor > 0) {
sign = -1;
}
long tmp = l2;
int bit = 1;
while ((l1 >> 1) >= tmp) {
tmp <<= 1;
bit <<= 1;
}
int res = 0;
while (l1 >= l2) {
if (l1 >= tmp) {
res += bit;
l1 -= tmp;
}
tmp >>= 1;
bit >>= 1;
}
return sign * res;
}
}
没有评论:
发表评论