Implement int sqrt(int x).
Compute and return the square root of x.
Example
sqrt(3) = 1
sqrt(4) = 2
sqrt(5) = 2
sqrt(10) = 3
Challenge
O(log(x))
求非线性方程的解可以使用二分法。当然前提是该方程所表示的函数在一定区间内与x的交点只有一个。
x√
x√<=(x+1)/2
class Solution {
public:
/**
* @param x: An integer
* @return: The sqrt of x
*/
int sqrt(int x) {
// write your code here
if (x < 0){
return -1;
}
long long l = 0, r = x/2+1;
while (l<=r){
long long mid = l + (r - l) / 2;
long long tmp = mid*mid - x;
if ( tmp== 0){
return mid;
}
else if (tmp>0){
r = mid-1;
}
else{
l = mid+1;
}
}
return r;//return l出错
}
};
还有牛顿迭代法可以求平方根