[LeetCode]#69. Sqrt(x)

Fatboy Slim
1 min readApr 3, 2020

Environment: Python 3.7

Key technique: Binary Search, //

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 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.

Analysis:

Use binary search to find ans. If input is 1, just return answer 1. The brief process is as below.

Solution:

class Solution(object):
def mySqrt(self, num):

left = 0
right = num

while(left <= right):
mid = (left + right)//2

if(mid**2 < num):
left = mid + 1

elif(mid**2 > num):
right = mid -1

else:
return mid
if num==1:
return 1
else:
return left -1

Submitted result:

Reference:

https://leetcode.com/problems/sqrtx/discuss/557168/python-binary-search-92.59

--

--