高编课后作业------第九周-LeetCode-69.x的平方根

要考试了,刷一道水题...


有很多方法,牛顿迭代、割线等等,不过只需要整数,所以最快的是二分,使用特殊的整数二分就可以了:

class Solution:
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x==0:
            return 0
        if x==1:
            return 1
        x1 = 1
        x2 = x-1
        mid = 0
        while x1+1<x2:
            mid = int((x1+x2)/2)
            t = mid*mid
            if t > x:
                x2 = mid
            elif t < x:
                x1 = mid
            else:
                return mid
        return x1

猜你喜欢

转载自blog.csdn.net/syyjiang/article/details/80207841