Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode
029. Divide, integers (Medium)
links:
Title: https://oj.leetcode.com/problems/divide-two-integers/
Code (GitHub): Https://github.com/illuz/leetcode
Test Instructions:
To achieve division, you cannot use multiply, divide, and modulo.
Analysis:
You can't use multiply, divide, and modulo, and the rest, plus, minus, and bitwise operations.
- Will think of is to reduce again and again, but this will time out.
- On the basis of 1 optimization, as fast as the power, each time the divisor doubled (with a bitwise operation can be).
There is a hole here, that is, the result may be super int range, so it is best to use a long long to process, and then go Int.
Code:
C++:
Class Solution {public: int divide (int dividend, int divisor) {ll a = Dividend >= 0? Dividend:-(LL) Dividend;ll b = Divisor >= 0? Divisor:-(LL) Divisor;ll result = 0, c = 0;bool sign = (Dividend > 0 && divisor < 0) | | (Dividend < 0 && divisor > 0); while (a >= b) {c = b;for (int i = 0; a >= C; i++, C <<= 1) {A-= C;result + = (1<<i);}} if (sign) {return Max ((LL) int_min,-result);} else {return MIN ((ll) int_max, result);}} ;
Python:
Class solution: # @return An integer def divide (self, dividend, divisor): sign = (Dividend < 0 and divisor > 0) or (Dividend > 0 and Divisor < 0) A, B = ABS (dividend), ABS (divisor) ret, c = 0, 0 while a >= B: C = b i = 0 while a >= C: A-= c ret + = (1<<i) i + = 1 c <<= 1 if Si GN: ret =-ret return min (max ( -2147483648, ret), 2147483647)
[Leetcode] 029. Divide integers (Medium) (C++/python)