Skip to content

Commit 9bf92a5

Browse files
committed
🐱(binary-search): 50. Pow(x, n)
1 parent f3e9651 commit 9bf92a5

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,39 @@ class Solution(object):
210210
return left
211211
```
212212

213+
## 50. Pow(x, n)
214+
215+
[原题链接](https://leetcode-cn.com/problems/powx-n/)
216+
217+
### 思路:二分
218+
219+
利用分治的思想,$x^2n$ 均可以写作 $x^n * x^n$。
220+
221+
递归:
222+
223+
```go
224+
func myPow(x float64, n int) float64 {
225+
if n >= 0 {
226+
return quickMul(x, n)
227+
}
228+
return 1 / quickMul(x, -n)
229+
}
230+
231+
func quickMul(x float64, n int) float64 {
232+
if n == 0 {
233+
return 1
234+
}
235+
if n == 1 {
236+
return x
237+
}
238+
y := quickMul(x, n / 2)
239+
if n % 2 == 0 {
240+
return y * y
241+
} else {
242+
return y * y * x
243+
}
244+
}
245+
```
213246

214247
## 69. x 的平方根
215248

0 commit comments

Comments
 (0)