leetcode50 Pow(x, n)-zh
# 50. Pow(x, n) (opens new window)
English Version (opens new window)
# 题目描述
实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。
示例 1:
输入:x = 2.00000, n = 10 输出:1024.00000
示例 2:
输入:x = 2.10000, n = 3 输出:9.26100
示例 3:
输入:x = 2.00000, n = -2 输出:0.25000 解释:2-2 = 1/22 = 1/4 = 0.25
提示:
-100.0 < x < 100.0
-231 <= n <= 231-1
-104 <= xn <= 104
# 解法
# Python3
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1
if n < 0:
return 1 / self.myPow(x, -n)
y = self.myPow(x, n >> 1)
return y * y if (n & 1) == 0 else y * y * x
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# Java
class Solution {
public double myPow(double x, int n) {
long N = n;
return N >= 0 ? pow(x, N) : 1.0 / pow(x, -N);
}
public double pow(double x, long N) {
if (N == 0) {
return 1.0;
}
double y = pow(x, N >> 1);
return (N & 1) == 0 ? y * y : y * y * x;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# TypeScript
function myPow(x: number, n: number): number {
let res = 1;
if (n < 0) {
n = -n;
x = 1 / x;
}
for (let i = n; i != 0; i = Math.floor(i / 2)) {
if ((i & 1) == 1) {
res *= x;
}
x *= x;
}
return res;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# ...
1
编辑 (opens new window)
上次更新: 2021/10/30, 12:58:38