Description:
Implement pow(x, n).
Link:
https://leetcode.com/problems/powx-n/#/description
解题方法:
用2为底数的幂来代替n的线性增长,方法很容易想到,解法有多种,这道题的难点主要在于针对各种边界情况的处理在写代码时容易疏忽,导致不能bug free。
比如:n < 0
, n = INT_MAX
或 INT_MIN
Time Complexity:
O(logN)
完整代码:
double myPow(double x, int n)
{
return impPow(x, n);
}
double impPow(double x, long n) //当n = INT_MIN
{
if(n < 0) //当n < 0
return impPow(1/x, -n);
if(n == 0)
return 1;
if(n == 1)
return x;
double pow = x;
long times = 2; //当n = INT_MAX
while(times <= n)
{
pow *= pow;
times <<= 1;
}
times >>= 1;
return pow * impPow(x, n - times);
}