-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDivideTwoIntegers.py
66 lines (60 loc) · 1.75 KB
/
DivideTwoIntegers.py
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
54
55
56
57
58
59
60
61
62
63
64
65
66
class Solution:
# @return an integer
def divide(self, dividend, divisor):
sign = 1 if (dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0) else -1
sum = 0
count = 0
quotient = 0
dividend = abs(dividend)
divisor = abs(divisor)
while dividend >= divisor:
sum = divisor
count = 1
while sum + sum <= dividend:
sum += sum
count += count
dividend -= sum
quotient += count
return quotient*sign
class Solution2:
# @return an integer
def divide(self, dividend, divisor):
sign = 1 if (dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0) else -1
dividend = abs(dividend)
divisor = abs(divisor)
quotient = 0
while dividend >= divisor:
k = 0
tmp = divisor
while dividend >= tmp:
quotient += 1<<k
dividend -= tmp
tmp <<= 1
k += 1
return quotient*sign
s = Solution()
a = s.divide(-7,3)
print a
"""
class Solution:
# @return an integer
def divide(self, dividend, divisor):
if divisor == 0:
return False
if dividend == 0:
return 0
a = 0
if (dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0):
dividend = abs(dividend)
divisor = abs(divisor)
while dividend >= divisor:
a += 1
dividend -= divisor
else:
dividend = abs(dividend)
divisor = abs(divisor)
while dividend > 0:
a -= 1
dividend -= divisor
return a
"""