Pow(x,n) 求x的n次方。需要用到分治法,x^n = x^n/2 * x^n/2 *x^n%2
代码如下:
class Solution {
public:
double pow(double x, int n) {
if(n>=0){
return recurse_pow(x,n);
}
else if(n<0){
return 1.0/recurse_pow(x,-n);
}
}
double recurse_pow(double x,int n){
if(n==0){
return 1.0;
}
double m=recurse_pow(x,n/2);
if(n%2==0){
return m*m;
}
else{
return m*m*x;
}
}
};
sqrt(x) 求x的近似平方根 使用二分查找法 left=1,right=x/2
代码如下:
class Solution {
public:
int sqrt(int x) {
int left=1;
int right=x/2;
int mid,ret=0;
if(x<2){
return x;
}
while(left<=right){
mid=(left+right)/2;
if(x/mid>mid){
left=mid+1;
ret=mid;
}
else if(x/mid<mid){
right=mid-1;
}
else{
return mid;
}
}
return ret;
}
};