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