Pow(x,n):
class Solution {
public:
double pow(double x, int n) {
if(x == 0){
cout<<"NaN"<<endl;
return -1;
}
if(n == 0){
return 1;
}
int sign = (x < 0 && (n & 1)) ? -1 : 1;
x = abs(x);
if(x == 1){
return sign;
}
bool inverse = n < 0 ? true : false;
double origin_x = 1;
if(n == INT_MIN){
n = INT_MAX;
origin_x = x;
}else{
n = abs(n);
}
double ans = 1;
while(n){
if(n & 1){
ans *= x;
}
x *= x;
n = n >> 1;
}
ans *= sign;
return inverse ? 1 / (ans * origin_x) : ans * origin_x;
}
};
Sqrt(x):
class Solution {
public:
int sqrt(int x) {
if (x <= 0) return 0;
double last = 0;
double res = 1;
while (res != last)
{
last = res;
res = (res + x / res) / 2;
}
return int(res);
}
};
上述采用了 牛顿迭代法,以下摘自百度百科
这里我们设f(x)=x^2 - n,因此x1=x0-(x0^2-n)/2x0 = x0-x0/2+n/2X0=(x0+n/x0)/2