Skip to content

Commit 1319492

Browse files
authored
docs: add a description of the solution to lcci problem: No.08.05 (#761)
No.08.05.Recursive Mulitply
1 parent 2728bc7 commit 1319492

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

lcci/08.05.Recursive Mulitply/README.md

+53
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,59 @@
3131

3232
<!-- 这里可写通用的实现逻辑 -->
3333

34+
~~**最佳方案:**~~
35+
36+
~~直接返回 `A * B`~~
37+
38+
正常递归,叠加总和
39+
40+
```txt
41+
MULTIPLY(A, B)
42+
if A == 0 || B == 0
43+
return 0
44+
A + multiply(A, B - 1)
45+
```
46+
47+
优化 1:
48+
49+
由数值较小的数字决定递归层次
50+
51+
```txt
52+
MULTIPLY(A, B)
53+
if A == 0 || B == 0
54+
return 0
55+
return max(A, B) + multiply(max(A, B), min(A, B) - 1)
56+
```
57+
58+
优化 2:
59+
60+
使用位移减少递归层次
61+
62+
```txt
63+
MULTIPLY(A, B)
64+
return (B % 1 == 1 ? A : 0) + (B > 1 ? MULTIPLY(A + A, B >> 1) : 0)
65+
```
66+
67+
可进一步,转换为循环,虽然并不符合递归主题。
68+
69+
> A 与 B 皆为**正整数**,初始值不会为 0,所以终止条件是 `B != 1`
70+
71+
```txt
72+
MULTIPLY(A, B)
73+
T = min(A, B)
74+
A = max(A, B)
75+
B = T
76+
r = 0
77+
while B != 1 {
78+
if B % 2 == 1 {
79+
r = r + A
80+
}
81+
A = A + A
82+
B = B >> 1
83+
}
84+
return res + A
85+
```
86+
3487
<!-- tabs:start -->
3588

3689
### **Python3**

0 commit comments

Comments
 (0)