https://leetcode.com/problems/powx-n/
本题可采用二分法+递归解。以下是c++和python的代码。时间复杂度是O(log(n)),空间复杂度是O(log(n))。本题还有一种解法,就是以2为基数进行迭代,可参考:https://blog.csdn.net/linhuanmars/article/details/20092829
struct Solution {
double myPow(double x, int n) {
if (n == 0)
return 1.0;
double half = pow(x, n/2);
if (n%2 == 0)
return half*half;
return half*half*(n>0?x:1/x);
}
};
class Solution:
def myPow(self, x, n):
if n == 0:
return 1.0;
half = self.myPow(x, int(n/2))
if n % 2 == 0:
return half * half
if n > 0:
return half * half * x
return half * half / x