Skip to content

Commit e50420a

Browse files
committed
Divide Two integers
1 parent 6152f7a commit e50420a

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

29_divide_two_integers.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# class Solution(object):
2+
# def divide(self, dividend, divisor):
3+
# """
4+
# :type dividend: int
5+
# :type divisor: int
6+
# :rtype: int
7+
# """
8+
9+
import math
10+
11+
class Solution(object):
12+
def divide(self, dividend, divisor):
13+
if divisor == 0:
14+
return MAX_INT
15+
if dividend == 0:
16+
return 0
17+
isPositive = (dividend < 0) == (divisor < 0)
18+
m = abs(dividend)
19+
n = abs(divisor)
20+
# ln and exp
21+
res = math.log(m) - math.log(n)
22+
res = int(math.exp(res))
23+
if isPositive:
24+
return min(res, 2147483647)
25+
return max(0 - res, -2147483648)
26+
27+
# def divide(self, dividend, divisor):
28+
# # (dividend >= 0) ^ (divisor < 0)
29+
# isPositive = (dividend < 0) == (divisor < 0)
30+
# dividend, divisor, result = abs(dividend), abs(divisor), 0
31+
# while dividend >= divisor:
32+
# n, nb = 1, divisor
33+
# # fast minus
34+
# while dividend >= nb:
35+
# dividend, result = dividend - nb, result + n
36+
# n, nb = n << 1, nb << 1
37+
# if isPositive:
38+
# return min(result, 2147483647)
39+
# return max(-result, -2147483648)
40+
41+
if __name__ == '__main__':
42+
s = Solution()
43+
print s.divide(1, 1)
44+
45+

0 commit comments

Comments
 (0)