//递归求解,每次都求N/2,直到N为0或1
class Solution {
public:
double myPow(double x, int n) {
if (n == 0) {return 1;}
if (n == 1) {return x;}
long long N = n;//因为如果 n = -2^31,那么后面 num = -num = 2^31,用 int 的话会溢出
if (N < 0) {
N = -N;
x = 1/x;
}
double half = myPow(x, int(N/2));
return N%2 ? half*half*x : half*half;
}
};
作者:zhu-que-3
链接:https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/solution/cdi-gui-by-zhu-que-3-6ltw/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
完整代码:实在想不通递归跟着调一遍就好了
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
double myPow(double x, int n) {
if (n == 0) { return 1; }
if (n == 1)
{ return x; }
long long N = n;//因为如果 n = -2^31,那么后面 num = -num = 2^31,用 int 的话会溢出
if (N < 0) {
N = -N;
x = 1 / x;
}
double half = myPow(x, int(N / 2));
return N % 2 ? half*half*x : half*half;
}
};
int main(){
Solution a;
cout<<a.myPow(3, 4)<<endl;
system("pause");
return 0;
}