Description
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
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842…, and since the decimal part is truncated, 2 is returned.
Submissions
两种解题思路,一种直接令x开平方并取整返回即可。
实现代码如下:
class Solution:
def mySqrt(self, x: int) -> int:
return int(x ** (1/2))
另一种采用二分法,在0到x中找最接近解的值。并在最小区间内,考虑将小数位省略,因此需要在最后判断并选择平方后小于x的解。
实现代码如下:
class Solution:
def mySqrt(self, x: int) -> int:
l, r = 0, x
mid = (l + r) //2
while r > l+1:
if mid **2 < x :
l = mid
else :
r = mid
mid = (l + r) //2
if r**2 > x:
return l
else:
return r