Problem: Implement the library function implement Pow(x, n)
Solution: 该博客给出了几种不同的解题思路,值得参考。
http://blog.csdn.net/fengbingyang/article/details/12236121
下面给出其中一种AC 6ms的代码实现
class Solution {
public:
double myPow(double x, int n) {
if (n == 0)
return 1.0;
else {
if (n < 0)
{
//判断是否溢出
if (n == INT_MIN)
return 1.0 / (pow(x, INT_MAX)*x);
else
return 1.0 / pow(x, -n);
}else{
if (n % 2 == 0)
{
double temp = myPow(x, n >> 1);
return temp * temp;
}
else{
double temp = myPow(x, (n - 1) >> 1);
return temp * temp * x;
}
}//else
}//else
}
};