LeetCode - Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

 

Example 1:

Input: 4

Output: 2

 

Example 2:

Input: 8

Output: 2

Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.

========================================================================================
class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x == 0:
            return 0
        
        L0 = len(str(x))
        L = L0/2
        
        if(L0/2.0-L)>0:
            L +=1

        left = 10**(L - 1)
        right = 10**L
        
        while True:
            mid = (left+right)/2
            if mid * mid > x:
                right = mid
            elif mid*mid <=x and (mid+1)*(mid+1) > x:
                return mid
            else:
                left = mid
                
            
test = Solution()

print test.mySqrt(123)

 From web http://bookshadow.com/weblog/2015/08/29/leetcode-sqrtx/ :

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

 

posted @ 2017-12-18 15:09  YWU  阅读(72)  评论(0)    收藏  举报