File tree Expand file tree Collapse file tree 3 files changed +98
-0
lines changed Expand file tree Collapse file tree 3 files changed +98
-0
lines changed Original file line number Diff line number Diff line change
1
+ # [ 面试题16. 数值的整数次方] ( https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/ )
2
+
3
+ ## 题目描述
4
+ 实现函数 double Power(double base, int exponent),求 base 的 exponent 次方。不得使用库函数,同时不需要考虑大数问题。
5
+
6
+ ** 示例 1:**
7
+
8
+ ```
9
+ 输入: 2.00000, 10
10
+ 输出: 1024.00000
11
+ ```
12
+
13
+ ** 示例 2:**
14
+
15
+ ```
16
+ 输入: 2.10000, 3
17
+ 输出: 9.26100
18
+ ```
19
+
20
+ ** 示例 3:**
21
+
22
+ ```
23
+ 输入: 2.00000, -2
24
+ 输出: 0.25000
25
+ 解释: 2-2 = 1/22 = 1/4 = 0.25
26
+ ```
27
+
28
+ ** 说明:**
29
+
30
+ - ` -100.0 < x < 100.0 `
31
+ - n 是 32 位有符号整数,其数值范围是 ` [−231, 231 − 1] ` 。
32
+
33
+ ## 解法
34
+ ### Python3
35
+ ``` python
36
+ class Solution :
37
+ cache = {}
38
+ def myPow (self , x : float , n : int ) -> float :
39
+ self .cache = {}
40
+ return self .pow(x, n)
41
+
42
+ def pow (self , x , n ):
43
+ if self .cache.get(' {} -{} ' .format(x, n)):
44
+ return self .cache[' {} -{} ' .format(x, n)]
45
+ if n == 0 : return 1
46
+ if n == 1 : return x
47
+ if n == - 1 : return 1 / x
48
+
49
+ half = self .pow(x, n // 2 )
50
+ self .cache[' {} -{} ' .format(x, n // 2 )] = half
51
+ return half * half * self .pow(x, n % 2 )
52
+ ```
53
+
54
+ ### Java
55
+ ``` java
56
+ class Solution {
57
+ public double myPow (double x , int n ) {
58
+ if (n == 0 ) return 1 ;
59
+ if (n == 1 ) return x;
60
+ if (n == - 1 ) return 1 / x;
61
+ double half = myPow(x, n / 2 );
62
+ return half * half * myPow(x, n % 2 );
63
+ }
64
+ }
65
+ ```
66
+
67
+ ### ...
68
+ ```
69
+
70
+ ```
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public double myPow (double x , int n ) {
3
+ if (n == 0 )
4
+ return 1 ;
5
+ if (n == 1 )
6
+ return x ;
7
+ if (n == -1 )
8
+ return 1 / x ;
9
+ double half = myPow (x , n / 2 );
10
+ return half * half * myPow (x , n % 2 );
11
+ }
12
+ }
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ cache = {}
3
+ def myPow (self , x : float , n : int ) -> float :
4
+ self .cache = {}
5
+ return self .pow (x , n )
6
+
7
+ def pow (self , x , n ):
8
+ if self .cache .get ('{}-{}' .format (x , n )):
9
+ return self .cache ['{}-{}' .format (x , n )]
10
+ if n == 0 : return 1
11
+ if n == 1 : return x
12
+ if n == - 1 : return 1 / x
13
+
14
+ half = self .pow (x , n // 2 )
15
+ self .cache ['{}-{}' .format (x , n // 2 )] = half
16
+ return half * half * self .pow (x , n % 2 )
You can’t perform that action at this time.
0 commit comments