题目
Implement int sqrt(int x)
.
Compute and return the square root of x, where x is
guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated
and only the integer part of the result is returned.
Example 1:
Example 2:
1 2 3 4
| Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
|
题解
二分法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: int mySqrt(int x) { int left=0,right=x,ans=-1; while(left<=right) { int mid=(left+right)/2; if((long long)mid*mid>x) right=mid-1; else if(mid*mid<x) { ans=mid; left=mid+1; } else return mid; } return ans; } };
|
牛顿迭代法
相当于求\(x^2-C=0\)的零点,从\(x=C\)开始找改点切线与x轴的交点,作为下一次起点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public: int mySqrt(int x) { if (x == 0) { return 0; }
double C = x, x0 = x; while (true) { double xi = 0.5 * (x0 + C / x0); if (fabs(x0 - xi) < 1e-7) { break; } x0 = xi; } return int(x0); } };
|