Skip to content

Commit 8bd6e4c

Browse files
committed
feat: add 050
1 parent 18032d4 commit 8bd6e4c

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@
6666
|33|[Search in Rotated Sorted Array][033]|Arrays, Binary Search|
6767
|43|[Multiply Strings][043]|Math, String|
6868
|49|[Group Anagrams][049]|Hash Table, String|
69+
|50|[Pow(x, n)][050]|Math, Binary Search|
6970
|554|[Brick Wall][554]|Hash Table|
7071

7172

@@ -129,6 +130,7 @@
129130
[033]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/033/README.md
130131
[043]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/043/README.md
131132
[049]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/049/README.md
133+
[050]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/050/README.md
132134
[554]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/554/README.md
133135

134136
[004]: https://github.com/Blankj/awesome-java-leetcode/blob/master/note/004/README.md

note/050/README.md

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# [Pow(x, n)][title]
2+
3+
## Description
4+
5+
Implement pow(x, n).
6+
7+
**Tags:** Math, Binary Search
8+
9+
10+
## 思路0
11+
12+
题意是让你计算`x^n`,如果直接计算肯定会超时,那么我们可以想到可以使用二分法来降低时间复杂度。
13+
14+
```java
15+
class Solution {
16+
public double myPow(double x, int n) {
17+
if (n < 0) return helper(1 / x, -n);
18+
return helper(x, n);
19+
}
20+
21+
private double helper(double x, int n) {
22+
if (n == 0) return 1;
23+
if (n == 1) return x;
24+
double d = helper(x, n >>> 1);
25+
if (n % 2 == 0) return d * d;
26+
return d * d * x;
27+
}
28+
}
29+
```
30+
31+
32+
## 结语
33+
34+
如果你同我一样热爱数据结构、算法、LeetCode,可以关注我GitHub上的LeetCode题解:[awesome-java-leetcode][ajl]
35+
36+
37+
38+
[title]: https://leetcode.com/problems/powx-n
39+
[ajl]: https://github.com/Blankj/awesome-java-leetcode
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.blankj.medium._050;
2+
3+
/**
4+
* <pre>
5+
* author: Blankj
6+
* blog : http://blankj.com
7+
* time : 2017/10/18
8+
* desc :
9+
* </pre>
10+
*/
11+
public class Solution {
12+
public double myPow(double x, int n) {
13+
if (n < 0) return helper(1 / x, -n);
14+
return helper(x, n);
15+
}
16+
17+
private double helper(double x, int n) {
18+
if (n == 0) return 1;
19+
if (n == 1) return x;
20+
double d = helper(x, n >>> 1);
21+
if (n % 2 == 0) return d * d;
22+
return d * d * x;
23+
}
24+
25+
public static void main(String[] args) {
26+
Solution solution = new Solution();
27+
System.out.println(solution.myPow(8.88023, 3));
28+
}
29+
}

0 commit comments

Comments
 (0)