LeetCode OJ 50. Pow(x, n)
Description
Implement pow(x, n).
解题思路
最简单的思路是循环n次,做n次乘法,这样的复杂度是O(n)
。但是有一种更好的做法:根据对称性,我们可以把前后n/2
个x
的乘积看成一个整体,如果n
为奇数,则这两部分相乘后只要再乘一次x就是最终结果;否则直接为所求结果。这样一直递归下去,每一次缩小的是当前x集合的1/2
。所以时间复杂度为O(logn)
。
代码
class Solution {
public:
double myPow(double x, int n) {
if(n == 0) return 1;
double t = myPow(x,n / 2);
if(n % 2) return n < 0 ? 1 / x * t * t : x * t * t;
else return t * t;
}
};