LeetCode-29 Divide Two Integers

Description

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:
Both dividend and divisor will be 32-bit signed integers.
The divisor will never be 0.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [− 2 31 2^{31} 231, 2 31 2^{31} 231 − 1]. For the purpose of this problem, assume that your function returns 2 31 2^{31} 231 − 1 when the division result overflows.

Example

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.

Submissions

因为此题不能直接利用乘法、除法和求余,所以我的解题思路是运用python的range() 函数生成一个整数列表,函数range(start, stop[, step])中,计数从 start 开始,默认是从 0 开始,到 stop 结束,但不包括 stop,step指代步长,默认为1。在此题中,首先记录flag正负号,然后将参数dividend和divisor取绝对值。去除dividend小于等于divisor的情况,再利用range()函数计算res结果,因为range() 函数返回的列表中不包括 stop,所以在解题时令dividend加一。得到列表后它的长度加上正负号即为此题结果,最后判断结果是否溢出,按要求返回结果即可。

实现代码如下:

class Solution:
    def divide(self, dividend: int, divisor: int) -> int:
        flag = 1
        if (dividend < 0 and divisor > 0) or (dividend >0 and divisor<0):
            flag = -1
        dividend, divisor = abs(dividend), abs(divisor)
        if dividend < divisor:
            return 0
        if dividend == divisor:
            return flag      
        res = flag*len(range(divisor,dividend+1,divisor)) 
        if res >= -(2**31) and res <= 2**31-1:
                return res
        else:
                return 2**31-1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值