29. Divide Two Integers

题目

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

题意

比较经典的一道题,一直做减法运算,结果时间复杂度超了,网上查了一下,就用移位做的
对于那个-2147483648,给出2147483647,是因为超出最大值就将最大值返回了,不过我这个没考虑最大值问题,只是加了一个测试用例,accepted

Python实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution(object):
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
if divisor == 0: return -1
if dividend==-2147483648 and divisor==-1:return 2147483647
num = 0
if (divisor > 0 and dividend > 0) or (divisor<0 and dividend<0): flag = 0
else:flag=1
dividend=abs(dividend)
divisor=abs(divisor)
while dividend >= divisor:
ni=1
temp=divisor
while temp<=dividend:
temp=temp<<1
if temp<=dividend:ni=ni<<1
dividend=dividend-(temp>>1)
num += ni
if flag == 1: return -num
return num
如果觉得有帮助,给我打赏吧!