-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathDivide Two Integers.py
More file actions
53 lines (39 loc) · 1.09 KB
/
Divide Two Integers.py
File metadata and controls
53 lines (39 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return 2147483647
Example
Given dividend = 100 and divisor = 9, return 11.
"""
__author__ = 'Daniel'
class Solution:
def divide(self, dividend, divisor):
q = 0
if dividend == 0 or divisor == 0:
return 0
# pitfall, overflow
MAXINT = 2147483647
MININT = -2147483648
if dividend == MININT and divisor == -1:
return MAXINT
sign = 1 if dividend*divisor > 0 else -1
dividend, divisor = abs(dividend), abs(divisor)
d = divisor
q_cur = 1
if divisor > dividend:
return 0
while d<<1 < dividend:
d <<= 1
q_cur <<= 1
q += q_cur
dividend -= d
while dividend:
if divisor > dividend:
break
while d > dividend:
d >>= 1
q_cur >>= 1
q += q_cur
dividend -= d
return q*sign
if __name__ == "__main__":
print Solution().divide(-1, 1)