Skip to content

Commit fac5dd7

Browse files
author
Liu Jie
committed
两数相除-中等
0 parents  commit fac5dd7

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.idea

practice/divide_two_integers.py

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#!/usr/bin/env python
2+
# coding=utf-8
3+
4+
"""
5+
给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。
6+
7+
返回被除数 dividend 除以除数 divisor 得到的商。
8+
9+
来源:力扣(LeetCode)
10+
链接:https://leetcode-cn.com/problems/divide-two-integers
11+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
12+
"""
13+
14+
15+
def divide(dividend, divisor):
16+
is_negative = (dividend < 0) != (divisor < 0)
17+
if dividend < 0:
18+
dividend = -dividend
19+
if divisor < 0:
20+
divisor = -divisor
21+
22+
i = 0
23+
step = divisor
24+
step_count = 1
25+
begin_reduce = False
26+
27+
step_list = []
28+
index = 0
29+
while dividend >= divisor:
30+
31+
# print(dividend, step)
32+
while dividend < step and index >= 0:
33+
step, step_count = step_list[index]
34+
index -= 1
35+
36+
if index < 0 and dividend < step:
37+
break
38+
39+
dividend -= step
40+
i += step_count
41+
42+
if not begin_reduce:
43+
step_list.append((step, step_count))
44+
step += step
45+
step_count += step_count
46+
index = len(step_list) - 1
47+
48+
if is_negative:
49+
return max(-i, -1 << 31)
50+
return min(i, (1 << 31) - 1)
51+
52+
53+
def main():
54+
cases = [
55+
(10, 3, 3),
56+
(7, -3, -2),
57+
(4294967296, -1, -2147483648)
58+
]
59+
60+
for dd, dr, r in cases:
61+
result = divide(dd, dr)
62+
if result != r:
63+
print('{} / {} != {}, {}'.format(dd, dr, result, r))
64+
exit(-1)
65+
print('pass')
66+
67+
68+
if __name__ == '__main__':
69+
main()

0 commit comments

Comments
 (0)