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 484dd69

Browse files
🐱(binary-search): 50. Pow(x, n)
补充 Python 题解
1 parent 2a49187 commit 484dd69

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

‎docs/algorithm/research/binary-search/README.md‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -288,12 +288,35 @@ class Solution(object):
288288

289289
[原题链接](https://leetcode-cn.com/problems/powx-n/)
290290

291-
### 思路:二分
291+
### 思路:快速幂
292292

293293
利用分治的思想,$x^2n$ 均可以写作 $x^n * x^n$。
294294

295295
递归:
296296

297+
<!-- tabs:start -->
298+
299+
#### **Python**
300+
301+
```python
302+
class Solution:
303+
def myPow(self, x: float, n: int) -> float:
304+
def fast_pow(x, n):
305+
if n == 0:
306+
return 1
307+
308+
fast_res = fast_pow(x, n//2)
309+
if n % 2 == 0:
310+
return fast_res * fast_res
311+
else:
312+
return fast_res * fast_res * x
313+
314+
res = fast_pow(x, abs(n))
315+
return res if n > 0 else 1/res
316+
```
317+
318+
#### **Go**
319+
297320
```go
298321
func myPow(x float64, n int) float64 {
299322
if n >= 0 {
@@ -318,6 +341,8 @@ func quickMul(x float64, n int) float64 {
318341
}
319342
```
320343

344+
<!-- tabs:end -->
345+
321346
## 69. x 的平方根
322347

323348
[原题链接](https://leetcode-cn.com/problems/sqrtx/comments/)

0 commit comments

Comments
(0)

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