Pow(x, n)
思路:x^n=(x*x)^(n/2),当n为偶数;x^n=(x*x)^(n/2)*x,当n为奇数.
当n为负数时,x^n=(1/x)^(-n)
注意:对边界条件的处理,当n=INT_MIN时,直接取负会溢出。
https://discuss.leetcode.com/topic/5425/short-and-easy-to-understand-solution
class Solution {
public:
double myPow(double x, int n) {
if(n==0)
return 1;
if(n<0)
{
if(n==INT_MIN) //注意对此临界情况的处理,如果直接取n=-n,会溢出
return myPow(x,n+1)/x;//INT_MIN+1防止取负溢出
else return myPow(1/x,-n);
}
return (n%2==0)?myPow(x*x,n>>1):myPow(x*x,n>>1)*x;
}
};
时间复杂度:O(lgn)