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.
解答:
https://kingsfish.github.io/2017/10/11/Leetcode-29-Divide-Two-Integers/
class Solution {
public static void main(String[] args) {
int ff = divide(7,3);
}
public static int divide(int dividend, int divisor) {
if(dividend == Integer.MIN_VALUE && divisor == -1)return Integer.MAX_VALUE;
if(dividend == Integer.MAX_VALUE && divisor == 1)return Integer.MAX_VALUE;
if(dividend == Integer.MIN_VALUE && divisor == 1)return Integer.MIN_VALUE;
if(dividend == Integer.MAX_VALUE && divisor == -1)return Integer.MIN_VALUE;
if(dividend == 0)return 0;
boolean sign = true;
if((dividend>0&&divisor<0)||(dividend<0&&divisor>0))sign = false;
//处理符号
long dividend1 = dividend>0?dividend:0l-dividend;
long divisor1 = divisor>0?divisor:0l-divisor;
long sum = divisor1;
int carry = 0;//记录走过多少轮
int l = 1;
while(sum<=dividend1){
divisor1 = divisor1<<1;
sum = sum + divisor1;
l = l<<1;
carry++;
}
sum = 0;
int res = 0;
while(carry>=0){
sum = sum + divisor1;
if(sum<=dividend1){
res = res + l ;
}else{
sum = sum-divisor1;
}
divisor1 = divisor1>>1;
l = l>>1;
carry--;
}
if(!sign)res = -res;
return res;
}
}