难度:中等
实现 pow(x, n) ,即计算 x 的 n 次幂函数。
示例 1:
输入: 2.00000, 10
输出: 1024.00000
示例 2:
输入: 2.10000, 3
输出: 9.26100
示例 3:
输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
说明:
- -100.0 < x < 100.0
- n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。
题目解析:(这里根本没考虑溢出的问题)
主要考虑以下几个问题,x==0,n==0,n>0,n<0等几种情况,还有一个double类型数据的比较。
这里使用一般的暴力法会超时,所以使用分治+递归思想。
x -> x^2 -> x^4 -> x^8 -> x^16......以此类推。我们这里需要倒过来看(从右往左),因为我们不知道什么时候乘到n。分为以下两种情况:
(1)偶数: x^(n/2) = y -> x^n = y^2
(2) 奇数: x^(n/2) = y -> x^n = y^2*x
参考代码:(暴力法超时)
class Solution {
public:
double myPow(double x, int n) {
double exp = 0.000001;
if (x >= -exp && x <= exp)
return 0.0;
bool n_flag = false;
if (n == 0 || abs(x-1) >= -exp && abs(x-1) <= exp)
return 1.0;
else if (n < 0)
{
n_flag = true;
n = -n;
}
double res = x;
for (int i = 1; i < n; i++)
{
res *= x;
}
if (n_flag)
res = 1 / res;
return res;
}
};
参考代码(分治+递归 时间复杂度为O(logn),空间复杂度为O(logn)):
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <deque>
#include <stack>
#include <algorithm>
#include <map>
using namespace std;
//分治+递归
class Solution {
public:
double quickMul(double x, int N) {
if (N == 0) {
return 1.0;
}
double y = quickMul(x, N / 2);
return N % 2 == 0 ? y * y : y * y * x;
}
double myPow(double x, int n) {
//第一个情况已经考虑了n==0的情况,分为大于0小于0两种情况
return n >= 0 ? quickMul(x, n) : 1.0 / quickMul(x, -n);
}
};
int main()
{
Solution solution;
double x = 2.0;
int n = 2147483647;
cout << solution.myPow(x,n) << endl;
system("pause");
return 0;
}