Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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)

AltStyle によって変換されたページ (->オリジナル) /