Topic Link: Divide two integers
Divide two integers without using multiplication, division and mod operator.
If It is overflow, return max_int.
The requirement of this problem is to divide the two integers without using multiplication, division, and modulo operation. If overflow, return max_int.
The direct idea of this problem is to use dividend to subtract the divisor until it is 0. The iteration number of this method is the size of the result, i.e. the result is n and the algorithm complexity is O (n).
The bitwise operation can be optimized by simulating the division operation on the computer. Converts integers into binary form, that is, num = a0*2^0 + a1*2^1 + a2*2^2 + ... + an*2^n. Based on this formula and the left one equivalent multiplied by 2, you can let the divisor move left until it is greater than dividend before getting a maximum cardinality. Then subtract this cardinality each time with dividend, and the result increases 2^k. Next, continue to move the divisor left to the left iteration until the divisor is not greater than the divisor. The time complexity is O (LOGN) because the iteration of this method is the power of 2 to the end.
It is important to note that the main point is to deal with symbols and overflow problems. For overflow problems, a long long can be used first, or whether the shift will overflow before the shift.
Complexity of Time: O (LOGN)
Complexity of Space: O (1)
1 class Solution
2 {
3 public:
4 int divide (int dividend, int divisor)
5 {
6 int sign = ( Dividend < 0) ^ (Divisor < 0)? -1:1;
7 Long Long res = 0, M = ABS ((long long) dividend), n = ABS ((long long) divisor);
8 while (M >= N)
9 { a long long T = n, i = 1;
One while (T << 1 < m) { t <<= 1; i <<= 1; m- = t; res = i; if (sign < 0) res =-res;
Return res > Int_max? Int_max:res;
23};
Reprint please explain source: Leetcode---29. Divide two integers