Skip to content

Commit f2fb908

Browse files
author
weiy
committed
divide two integers easy
1 parent 576937b commit f2fb908

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Number/DivideTwoIntegers.py

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""
2+
Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
3+
4+
Return the quotient after dividing dividend by divisor.
5+
6+
The integer division should truncate toward zero.
7+
8+
Example 1:
9+
10+
Input: dividend = 10, divisor = 3
11+
Output: 3
12+
Example 2:
13+
14+
Input: dividend = 7, divisor = -3
15+
Output: -2
16+
Note:
17+
18+
Both dividend and divisor will be 32-bit signed integers.
19+
The divisor will never be 0.
20+
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.
21+
22+
除以某数,其结果要尽可能趋向0的,且为整数。
23+
24+
直接用Python 中的地板除 // 即可。
25+
26+
判断两个数的符号是否相同和处理 2**31-1 和 -2**31 即可。
27+
28+
测试链接:
29+
https://leetcode.com/problems/divide-two-integers/description/
30+
31+
beat 100% 28ms.
32+
33+
这个题没什么意思...应该作为第二天的零启动任务来做,但已经做了,换一个零启动任务吧。
34+
35+
"""
36+
class Solution(object):
37+
def divide(self, dividend, divisor):
38+
"""
39+
:type dividend: int
40+
:type divisor: int
41+
:rtype: int
42+
"""
43+
44+
x = abs(dividend) // abs(divisor)
45+
if (dividend < 0 and divisor > 0) or (dividend > 0 and divisor < 0):
46+
47+
if -x < -2**31:
48+
return -2**31
49+
return -x
50+
51+
if x > 2**31-1:
52+
return 2**31-1
53+
return x
54+

0 commit comments

Comments
 (0)