# Sqrt(x) -- leetcode

Implement int sqrt(int x).

Compute and return the square root of x.

(n/2+1)2=n+1+n2/4>n$(n/2+1)^2=n+1+n^2/4>n$。因此只需要在[0, n/2+1]的区间内二分查找。

class Solution {
public:
int mySqrt(int x) {
long long low = 0;
long long high = x / 2 +1;
long long mid = 0, p = 0;
while(low <= high){
mid = (low + high)/2;
p = mid * mid;
if (p == x) return mid;
if (p < x) low = mid+1;
if (p > x) high = mid-1;
}
return high;
}
};

#include <iostream>
using namespace std;
double sqrt(double);
int main() {
double n;
while (cin >> n) {
double ans = sqrt(n);
cout << ans << endl;
}

system("pause");
return 0;
}
//判断两个doule类型的值是否相等
bool isEqual(double a, double b) {
if (abs(a - b) > 0.000001)
return false;
return true;
}
//牛顿迭代法求解
double sqrt(double n) {
double last = 0.0;//保存上一次的值
double res = 1.0;//最近一次的值，初始化
while (!isEqual(last, res)) {//不相等，继续搜索
last = res;//保存上一次的值
res = (res + n / res) / 2;//x_(i+1)=(x_i + n / x_i)/2
}
return res;
}

#### LeetCode Sqrt(x) 解题报告

2014-01-31 09:44:54

#### Sqrt(x) -- LeetCode

2014-02-28 01:06:21

#### Leetcode: Sqrt(x)

2013-10-07 21:56:53

#### LeetCode69 Sqrt(x)**

2015-04-03 10:17:40

#### Leetcode 69. Sqrt(x) 开根号 解题报告

2016-05-11 23:24:53

#### leetcode 日经贴，python code -Sqrt(x)

2015-02-13 12:44:26

#### LeetCode 69. Sqrt(x)（开平方根）

2016-05-22 00:05:17

#### LeetCode 69 — Sqrt(x)（C++ Java Python）

2014-02-26 21:39:03

#### [Java]Leetcode69 Sqrt(x)

2015-07-27 13:29:08

#### LeetCode-69-Sqrt(x) Python要用math.sqrt()

2017-09-20 22:43:15