实现 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
注意:本题与主站 50 题相同:https://leetcode.cn/problems/powx-n/
方法一:数学(快速幂)
快速幂算法的核心思想是将幂指数
时间复杂度
class Solution:
def myPow(self, x: float, n: int) -> float:
def qmi(a, k):
res = 1
while k:
if k & 1:
res *= a
a *= a
k >>= 1
return res
return qmi(x, n) if n >= 0 else 1 / qmi(x, -n)
class Solution {
public double myPow(double x, int n) {
long N = n;
return n >= 0 ? qmi(x, N) : 1.0 / qmi(x, -N);
}
private double qmi(double a, long k) {
double res = 1;
while (k != 0) {
if ((k & 1) != 0) {
res *= a;
}
a *= a;
k >>= 1;
}
return res;
}
}
class Solution {
public:
double myPow(double x, int n) {
long long N = n;
return N >= 0 ? qmi(x, N) : 1.0 / qmi(x, -N);
}
double qmi(double a, long long k) {
double res = 1;
while (k) {
if (k & 1) {
res *= a;
}
a *= a;
k >>= 1;
}
return res;
}
};
func myPow(x float64, n int) float64 {
if n >= 0 {
return qmi(x, n)
}
return 1.0 / qmi(x, -n)
}
func qmi(a float64, k int) float64 {
var res float64 = 1
for k != 0 {
if k&1 == 1 {
res *= a
}
a *= a
k >>= 1
}
return res
}
/**
* @param {number} x
* @param {number} n
* @return {number}
*/
var myPow = function (x, n) {
return n >= 0 ? qmi(x, n) : 1 / qmi(x, -n);
};
function qmi(a, k) {
let res = 1;
while (k) {
if (k & 1) {
res *= a;
}
a *= a;
k >>>= 1;
}
return res;
}
function myPow(x: number, n: number): number {
return n >= 0 ? qmi(x, n) : 1 / qmi(x, -n);
}
function qmi(a: number, k: number): number {
let res = 1;
while (k) {
if (k & 1) {
res *= a;
}
a *= a;
k >>>= 1;
}
return res;
}
public class Solution {
public double MyPow(double x, int n) {
long N = n;
return n >= 0 ? qmi(x, N) : 1.0 / qmi(x, -N);
}
private double qmi(double a, long k) {
double res = 1;
while (k != 0) {
if ((k & 1) != 0) {
res *= a;
}
a *= a;
k >>= 1;
}
return res;
}
}