Skip to content

Commit 0f9d1f9

Browse files
Add files via upload
1 parent d0d22e8 commit 0f9d1f9

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# 按位左移
2+
# 52ms 99.27%
3+
class Solution:
4+
def divide(self, dividend, divisor):
5+
"""
6+
:type dividend: int
7+
:type divisor: int
8+
:rtype: int
9+
"""
10+
# 注意判断正负号的方式!!!
11+
sign = (dividend < 0) is (divisor < 0)
12+
# 将两者都转换为正数去考虑
13+
dividend, divisor = abs(dividend), abs(divisor)
14+
res = 0
15+
while dividend >= divisor:
16+
temp, i = divisor, 1
17+
while dividend >= temp:
18+
dividend -= temp
19+
res += i
20+
i <<= 1
21+
temp <<= 1
22+
23+
# 判断正负号
24+
res = res if sign is True else - res
25+
26+
# 最终需要判断结果是否溢出
27+
if res > (2 << 30) - 1 or res < - (2 << 30):
28+
return (2 << 30) - 1
29+
else:
30+
return res

0 commit comments

Comments
 (0)