# 69. Sqrt(x)

Given a non-negative integer `x`, return the square root of`x` rounded down to the nearest integer. The returned integer should be non-negative as well.

You must not use any built-in exponent function or operator.

• For example, do not use `pow(x, 0.5)` in c++ or `x ** 0.5` in python.

Example 1:

``````Input: x = 4
Output: 2
Explanation: The square root of 4 is 2, so we return 2.
``````

Example 2:

``````Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.
``````

Constraints:

• `0 <= x <= 2^31 - 1`

``````class Solution {
public:
int mySqrt(int x) {
if (x <= 1) return x;
int left = 0, right = x;
while (left < right) {
int mid = left + (right - left) / 2;
if (x / mid >= mid) left = mid + 1;
else right = mid;
}
return right - 1;
}
};
``````

xi+1=xi - (xi2 - n) / (2xi) = xi - xi / 2 + n / (2xi) = xi / 2 + n / 2xi = (xi + n/xi) / 2

``````class Solution {
public:
int mySqrt(int x) {
if (x == 0) return 0;
double res = 1, pre = 0;
while (abs(res - pre) > 1e-6) {
pre = res;
res = (res + x / res) / 2;
}
return int(res);
}
};
``````

``````class Solution {
public:
int mySqrt(int x) {
long res = x;
while (res * res > x) {
res = (res + x / res) / 2;
}
return res;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/69

Pow(x, n)

Valid Perfect Square

https://leetcode.com/problems/sqrtx/description/

https://leetcode.com/problems/sqrtx/discuss/25130/My-clean-C++-code-8ms

https://leetcode.com/problems/sqrtx/discuss/25047/A-Binary-Search-Solution

https://leetcode.com/problems/sqrtx/discuss/25057/3-4-short-lines-Integer-Newton-Every-Language

LeetCode All in One 题目讲解汇总(持续更新中…)

（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，快快加入吧～）

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation