68ms Newton's method python code


  • 0
    Y
    class Solution:
        # @param {integer} x
        # @return {integer}
        def mySqrt(self, x):
            if x <= 0:
                return 0
    
            if x == 1:
                return 1
    
            d = x / 2
            pprev = 0
            prev = d
            d = (d + x / d) >> 1
            while d != prev:
                pprev = prev
                prev = d
                d = int(0.5 * (d + x / d))
    
                if pprev == d:
                    return min(prev, d)
            return d

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.