Sqrt(x) II – Python 3 (Week 11 – 01)

  class Solution:
    """
    @param x: a double
    @return: the square root of x
    """
    def sqrt(self, x):
        # write your code here
        if x < 1:
            start, end = x, 1
        else:
            start, end = 1, x
            
        
        while end - start > 1e-10:
            mid = start + (end  - start) / 2
            if mid * mid < x:
                start = mid
            else:
                end = mid
                
        return start
        
      

Time O(logn). Space O(1).

Leave a comment

Design a site like this with WordPress.com
Get started