法一:直接调用库函数,本题肯定不是用这种方法。(但是写在前面警示自己笔试时要变通hhh
int mySqrt(int x) {
return sqrt(x);
}
法二:二分法,注意非负数x的平方根<=x/2+1
int mySqrt(int x) {
int i=0;
int j=x/2+1;
while(i<=j){
long long mid=(i+j)/2;
long long res=mid*mid;
if(res==x) return mid;
else if(res>x) j=mid-1;
else i=mid+1;
}
return j;
}
执行用时 :4 ms, 在所有 C++ 提交中击败了96.52% 的用户
内存消耗 :8.3 MB, 在所有 C++ 提交中击败了74.54%的用户
法三:牛顿迭代法
int mySqrt(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;
}
执行用时 :4 ms, 在所有 C++ 提交中击败了96.52% 的用户
内存消耗 :8.4 MB, 在所有 C++ 提交中击败了73.49%的用户