实现 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
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
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;
}
}
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;
}