Ruka
1 min readJul 30, 2020

[LeetCode][python3]0029. Divide Two Integers

Start the journey
N2I -2020.07.27

  1. My first solution
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
d=False
if dividend<0:
d=not d
dividend=-dividend
if divisor<0:
divisor=-divisor
d=not d
res=dividend//divisor
if d:
res=-res
if res>2147483647:
return 2147483647
elif res<-2147483648:
return -2147483648
else:
return res

Explanation:

In other language, you have to deal with overflow problem. But Python 3 will fix that for you in default, so you have to use -2147483648≤res≤2147483647 to make sure the value isn’t out of range.

Note that a//b will have different answers from the problem description if a or b < 0, so we use a d to save the negative coefficient and calculate them in positive numbers.

Ruka
Ruka

Written by Ruka

HI I’m Ruka. Now a SWE in Taiwan. Contact via email: nayzi9999@gmail.com

No responses yet