Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode 029. Divide two integers (Medium) link :
Title: https://oj.leetcode.com/problems/divide-two-integers/
Code (GitHub): Https://github.com/illuz/leetcode :
To achieve division, you cannot use multiplication, division, and modulo. Analysis :
You can't use multiplication, divide and take modulo, the rest, plus, minus and bitwise operations. The idea is to subtract from time to time, but it will time out. On the basis of 1 optimization, like a fast power, the divisor doubled each time (using bit operation can).
There's a hole here, which means the result may be a range of int, so it's best to use long long, and then go Int. code :
C++:
Class Solution {public
:
int divide (int dividend, int divisor) {
ll a = Dividend >= 0? Dividend:-(LL) Div Idend;
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), or
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)