69. Sqrt(x)

原文题目:

Implement int sqrt(int x).

Compute and return the square root of x.

读题:

题目就是求x的开根号,很重要的一点是返回值是整数,而不是浮点数,因此这个开根号其实只是接近实际开根号的值的整数而已,并不是精确的开根号,因此可以采用二分法进行处理。

class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        if not x:
            return 0
        start = 1
        end = x//2 + 1  #取中间值,且为整数
        while start <= end:
            mid = int((start+end)/2)
            if mid**2 == x:
                return mid
            elif mid**2 >x:
                end = mid - 1
            else:
                start = mid + 1
        return end

  

原文地址:https://www.cnblogs.com/xqn2017/p/8006863.html