summary:
math
package myapp.kit.leetcode.top145;
/**
*
* 29
* medium
* https://leetcode.com/problems/divide-two-integers/
*
*
*
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, which means losing its fractional part. For example,
truncate(8.345) = 8 and truncate(-2.7335) = -2.
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Explanation: 10/3 = truncate(3.33333..) = 3.
Example 2:
Input: dividend = 7, divisor = -3
Output: -2
Explanation: 7/-3 = truncate(-2.33333..) = -2.
-2147483648
-1
-2147483648
1
-2147483648
-3
2147483647
3
-2147483648
1
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.
*
* @author huangdingsheng
* @version 1.0, 2020/6/4
*/
public class DivideTwoIntegers {
public static int divide(int dividend, int divisor) {
long dividend1 = dividend;
long divisor1 = divisor;
long quotient = 0;
int sign = 1;
if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)) {
sign = -1;
}
dividend1 = Math.abs(dividend1);
divisor1 = Math.abs(divisor1);
if (divisor1 > dividend1) {
return 0;
}
long temp = 0;
for (long i = 31; i >= 0; i--) {
if (temp + (divisor1 << i) <= dividend1) {
temp += divisor1 << i;
// | or + can be
quotient |= (1L << i);
}
}
long res = sign * quotient;
if (res > (2 << 30) - 1) {
return (2 << 30) - 1;
}
if (res < (- 2 << 30)) {
return -2 << 30;
}
return (int) (sign * quotient);
}
public static void main(String[] args) {
// System.out.println((2 << 30) - 1);
System.out.println(divide(-2147483648, -145));
System.out.println( (long)-2147483648 / (long)-145);
}
}