File tree 3 files changed +70
-0
lines changed
src/com/blankj/medium/_050
3 files changed +70
-0
lines changed Original file line number Diff line number Diff line change 66
66
| 33| [ Search in Rotated Sorted Array] [ 033 ] | Arrays, Binary Search|
67
67
| 43| [ Multiply Strings] [ 043 ] | Math, String|
68
68
| 49| [ Group Anagrams] [ 049 ] | Hash Table, String|
69
+ | 50| [ Pow(x, n)] [ 050 ] | Math, Binary Search|
69
70
| 554| [ Brick Wall] [ 554 ] | Hash Table|
70
71
71
72
129
130
[ 033 ] : https://github.com/Blankj/awesome-java-leetcode/blob/master/note/033/README.md
130
131
[ 043 ] : https://github.com/Blankj/awesome-java-leetcode/blob/master/note/043/README.md
131
132
[ 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
132
134
[ 554 ] : https://github.com/Blankj/awesome-java-leetcode/blob/master/note/554/README.md
133
135
134
136
[ 004 ] : https://github.com/Blankj/awesome-java-leetcode/blob/master/note/004/README.md
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments