29 Divide Two Integers
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
Input: dividend = 10, divisor = 3
Input: dividend = 7, divisor = -3
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.
You can use another artifact bit to operate Bit Manipulation. The idea is that if the dividend is greater than or equal to the divisor, the following loop is performed, defining the variable t to be equal to the divisor, and defining the count p. When twice t is less than or equal to the dividend, the following loop is performed, t Double the expansion, double the expansion of p, and then update res and m.
Some test cases given by the OJ of this question are very annoying, because the input is all int type, for example, the dividend is -2147483648, in the range of int, when the divisor is -1, the result exceeds the range of int, and INT_MAX needs to be returned.
So for this case, start with if judgment, and judge it together with the case where the divisor is 0, and return INT_MAX. Then the positive and negative of the return value must be determined according to the positive and negative of the dividend and the divisor. Here, the long integer type is used to complete all calculations, and the return value is multiplied by the sign.