时间复杂度(O(logn)),思想,二分查找
class Solution {
public:
int mySqrt(int x) {
if(x==0||x==1) return x;
int starti = 1;
int endi = x;
while(endi>starti)
if( x/((endi+starti)/2)<((endi+starti)/2))
endi = ((endi+starti)/2);
else if( x/((endi+starti)/2)>((endi+starti)/2)){
if(starti == ((endi+starti)/2))return starti;
starti = ((endi+starti)/2);
}else
return (endi+starti)/2;
return starti;
}
};
时间复杂度小于(O(logn)),思想,牛顿下山法
class Solution {
public:
int mySqrt(int x) {
if(x==0||x==1)return x;
int result =x/2;
while(!(result<x/result&&(result+1)>x/(result+1) || result==x/result )){
int mid_value = ((result+x/result)/2);
if(mid_value==result)return result;
result = mid_value;
}
return result;
}
};