leedcode解析—Python3—Divide Two Integers—Medium

题目
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

  1. transform dividend and divisor into string dividend = '888880', divisor = '33'
  2. pick the left len(divisor) of dividend '88', using a simple function to calculate the division and rem division = 2, rem = 22
  3. the division result is added to answer string ans = '2', and next digit of dividend is added to the rem '228'
  4. 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值