|
| 1 | +### [29\. Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) |
| 2 | + |
| 3 | +Difficulty: **Medium** |
| 4 | + |
| 5 | + |
| 6 | +Given two integers `dividend` and `divisor`, divide two integers without using multiplication, division and mod operator. |
| 7 | + |
| 8 | +Return the quotient after dividing `dividend` by `divisor`. |
| 9 | + |
| 10 | +The integer division should truncate toward zero. |
| 11 | + |
| 12 | +**Example 1:** |
| 13 | + |
| 14 | +``` |
| 15 | +Input: dividend = 10, divisor = 3 |
| 16 | +Output: 3``` |
| 17 | +
|
| 18 | +**Example 2:** |
| 19 | +
|
| 20 | +``` |
| 21 | +Input: dividend = 7, divisor = -3 |
| 22 | +Output: -2``` |
| 23 | + |
| 24 | +**Note:** |
| 25 | + |
| 26 | +* Both dividend and divisor will be 32-bit signed integers. |
| 27 | +* The divisor will never be 0. |
| 28 | +* Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2<sup>31</sup>, 2<sup>31</sup> − 1]. For the purpose of this problem, assume that your function returns 2<sup>31</sup> − 1 when the division result overflows. |
| 29 | + |
| 30 | + |
| 31 | +#### Solution |
| 32 | + |
| 33 | +Language: **Java** |
| 34 | + |
| 35 | +```java |
| 36 | +class Solution { |
| 37 | + public int divide(int dividend, int divisor) { |
| 38 | + boolean positive = false; |
| 39 | + if ((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)) { |
| 40 | + positive = true; |
| 41 | + } |
| 42 | + long longDividend = Math.abs((long) dividend); |
| 43 | + long longDivisor = Math.abs((long) divisor); |
| 44 | + |
| 45 | + long result = 0; |
| 46 | + while (longDividend >= longDivisor) { // 外层循环用来将剩余的继续算 |
| 47 | + long temp = longDivisor; |
| 48 | + long tempResult = 1; |
| 49 | + while (longDividend >= temp) { // 内层循环用来加快速度 |
| 50 | + longDividend -= temp; |
| 51 | + result += tempResult; |
| 52 | + tempResult <<= 1; |
| 53 | + temp <<= 1; |
| 54 | + } |
| 55 | + } |
| 56 | + if (positive && result > Integer.MAX_VALUE) { |
| 57 | + return Integer.MAX_VALUE; |
| 58 | + } |
| 59 | + if (!positive && result < Integer.MIN_VALUE) { |
| 60 | + return Integer.MIN_VALUE; |
| 61 | + } |
| 62 | + return positive ? (int) result : (int) -result; |
| 63 | + } |
| 64 | +} |
| 65 | +``` |
0 commit comments