Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 1091dfd

Browse files
committed
add 07
1 parent 5e320c3 commit 1091dfd

File tree

1 file changed

+44
-0
lines changed
  • leetcode刷题/note/6月刷题

1 file changed

+44
-0
lines changed

leetcode刷题/note/6月刷题/07.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# 50. Pow(x, n)
2+
实现 pow(x, n) ,即计算 x 的 n 次幂函数。
3+
4+
难度: `middle`
5+
6+
## 示例
7+
8+
```
9+
示例 1:
10+
11+
输入: 2.00000, 10
12+
输出: 1024.00000
13+
示例 2:
14+
15+
输入: 2.10000, 3
16+
输出: 9.26100
17+
```
18+
19+
## 解题思路
20+
21+
分治法,「快速幂算法」的本质是分治算法。举个例子,如果我们要计算x^64次幂 ,我们可以按照:
22+
23+
x -> x^2 -> x^4 -> x^8 -> x^{16} -> x^{32} -> x^{64}
24+
25+
分治的核心是递归,代码如下:
26+
27+
```javascript
28+
/**
29+
* @param {number} x
30+
* @param {number} n
31+
* @return {number}
32+
*/
33+
var myPow = function(x, n) {
34+
return n > 0 ? quickMul(x, n) : 1.0 / quickMul(x, -n);
35+
};
36+
37+
var quickMul = function(x, N) {
38+
if (N == 0) {
39+
return 1.0
40+
}
41+
let y = quickMul(x, Math.floor(N / 2));
42+
return N % 2 == 0 ? y * y : y * y * x;
43+
}
44+
```

0 commit comments

Comments
 (0)