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.
Input: 4
Output: 2
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
r = x
while r*r > x:
r = (r + x / r) / 2
return r
class Solution {
public:
int mySqrt(int x) {
if (x == 0) return 0;
int left = 1, right = x;
while (left <= right){
int mid = (left + right) / 2;
if (mid > x/mid) {
right = mid - 1;
} else {
if (mid + 1 > x/(mid + 1))
return mid;
left = mid + 1;
}
}
return right;
}
};
- 这是一个二分法的题目