Sqrt(x)

Problem: Sqrt(x)

This method can be solved by Newton's Iteration, which is a binary-search example in math problem.

Code in Python:

class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        if(x==0):
            return 0
        if(x<4):
            return 1
        middle=x//2
        while (middle*middle>x):
            middle=int(middle/2.0+x/(2.0*middle))
        return middle

results matching ""

    No results matching ""