Given two integers dividend
and divisor
, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend
by divisor
.
The integer division should truncate toward zero.
Example 1:
Input: dividend = 10, divisor = 3 Output: 3
Example 2:
Input: dividend = 7, divisor = -3 Output: -2
Note:
- Both dividend and divisor will be 32-bit signed integers.
- The divisor will never be 0.
- Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.
大概意思,不要用* / 取模 这三个符号来计算除法
boolean isMinedNeg = false;
boolean isMinsorNeg = false;
boolean isNeg = false;
if (dividend < 0) {
isNeg = true;
if (dividend == Integer.MIN_VALUE) {
dividend = Integer.MAX_VALUE;
isMinedNeg = true;
} else {
dividend = 0 - dividend;
}
}
if (divisor < 0) {
isNeg = !isNeg;
if (divisor == Integer.MIN_VALUE) {
divisor = Integer.MAX_VALUE;
isMinsorNeg = true;
} else {
divisor = 0 - divisor;
}
}
if(dividend < divisor || (isMinsorNeg && !isMinedNeg)) {
return 0;
}
int oldtemp = 0;
int oldcount = 0;
int sum = 0;
int mod = dividend - oldtemp;
while(mod >= divisor) {
int count = 1;
int temp = divisor;
while (mod >= temp) {
if(temp < 0) {
break;
}
oldtemp = temp;
oldcount = count;
temp += temp;
count = count<<1;
}
mod = mod - oldtemp;
sum += oldcount;
}
if(isNeg) {
sum = 0 - sum;
if(isMinedNeg && 1 + mod >= divisor) {
sum -= 1;
}
}
return sum;
我的大概思路,负数的全变成正数,不断的用1的两倍来解决效率的问题,举一个例子:60/3
1.3+3=6 <= 60 1*2=2
6+6=12 <= 60 2*2 =4
12+12=24 <= 60 4*2=8
24+24=48 <= 60 8*2=16
48+48=96 > 60 中断
2.因为60 -48 =12
3+3=6 <=
12 1*2=2
6+6=12 <= 12 2*2=4
12+12=24 > 12 中断
12-12=0
所以结果=16+4=20