square root of leetcode python x

implement the  int sqrt(int x) function.

Computes and returns  the square root of x  , where  is a nonnegative integer.

Since the return type is an integer, only the integer part of the result is retained, and the fractional part will be rounded off.

Example 1:

Inputs: 4
 Outputs: 2

Example 2:

Input: 8
 Output: 2
 Explanation: The square root of 8 is 2.82842...,
     Since the return type is an integer, the fractional part will be rounded off.

python code

class Solution:
    def mySqrt(self, x):
        left=0;right=x
        while left<right:
            mid=int((left+right)/2)
            if x<mid**2:
                right=mid
            else:
                left=mid+1
        if left>1:
            return left-1
        else:
            return left



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325687877&siteId=291194637