题目
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.
Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, assume that your function returns 231 − 1 when the division result overflows.
Example 1:
Input: dividend = 10, divisor = 3
Output: 3
Explanation: 10/3 = truncate(3.33333…) = 3.
Example 2:
Input: dividend = 7, divisor = -3
Output: -2
Explanation: 7/-3 = truncate(-2.33333…) = -2.
我的思路
When dividend is too large and divisor is too small, the algorism costs too much time. But if we transform these values into string and calculate by digits, code could be 10^digits faster.
Runtime: O(log(dividend)); 24 ms, faster than 97%.
Memory Usage: O(1)? [I am not sure for that : ( ]; 14.1 MB, less than 80%
How the algorism works:
example: dividend = 888880, divisor = 33
- transform dividend and divisor into string
dividend = '888880', divisor = '33'
- pick the left len(divisor) of dividend
'88'
, using a simple function to calculate the division and remdivision = 2, rem = 22
- the division result is added to answer string
ans = '2'
, and next digit of dividend is added to the rem'228'
- calculate the division and rem of the rem, loop, untill the lasted digit is added
88/33=[2, 22] --> 228/33=[6, 30] --> 308/33=[9, 11] --> 118/33=[3, 19] --> 190/33=[5, 25]
ans = 26935
我的解答:
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
positive = (dividend < 0) is (divisor < 0)
dividend = abs(dividend)
divisor = abs(divisor)
def div(x,y):
a = [-1,0]
if x < y:
a[0] = 0
a[1] = x
else:
while x >= 0:
x -= y
a[0] += 1
a[1] = x + y
return a
if dividend == 0 or dividend < divisor:
return 0
d = str(dividend)
s = str(divisor)
ans = ''
l = d[:len(s)-1]
for i in range(len(d)-len(s)+1):
l += d[len(s)-1+i]
t = div(int(l),int(s))
ans += str(t[0])
l = str(t[1])
ans = int(ans)
if not positive:
ans = -ans
if ans > 2**31-1 or ans < -2**31:
return 2**31-1
else:
return ans