剑指 Offer 16. 数值的整数次方

题目描述

实现 pow(xn) ,即计算 x 的 n 次幂函数(即,x^{n})。不得使用库函数,同时不需要考虑大数问题。

示例 1:

1
2
输入:x = 2.00000, n = 10
输出:1024.00000

示例 2:

1
2
输入:x = 2.10000, n = 3
输出:9.26100

示例 3:

1
2
3
输入:x = 2.00000, n = -2
输出:0.25000
解释:2-2 = 1/22 = 1/4 = 0.25

提示:

  • $-100.0 < x < 100.0$
  • $-2^{31} <= n <= 2^{31}-1$
  • $-10^{4} <= x^{n} <= 10^{4}$

注意:本题与主站 50 题相同:https://leetcode-cn.com/problems/powx-n/


算法

(快速幂) $O(logn))$

思路还是比较直接的,如果指数是负数,先不管负号,按正数来计算乘法的结果,最后再判断如果指数是负数的话,返回用 $1$ 除以答案的结果,否则直接返回即可。

注意:直接计算乘法会超时,需要用快速幂。

时间复杂度

$O(logn))$

空间复杂度

$O(1)$

C++ 代码

写法 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
double myPow(double x, int _n) {
if (!x || x == 1) return x;
long long n = _n;
bool is_minus = _n < 0;
n = is_minus ? -n : n;

// 快速幂
double res = 1;
while (n) {
if (n & 1) res = res * x;
x *= x;
n >>= 1;
}

return is_minus ? 1 / res : res;
}
};

写法 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
double myPow(double x, int n) {
typedef long long LL;
double res = 1;
bool is_minus = n < 0;

for (LL k = abs(LL(n)); k; k >>= 1) {
if (k & 1) res *= x;
x *= x;
}

if (is_minus) res = 1 / res;
return res;
}
};
Author: tonngw
Link: https://tonngw.com/2022/07/09/剑指 Offer/剑指 Offer 16. 数值的整数次方/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.