Leetcode 69. Sqrt(x)

Implement int sqrt(int x).

思路: Binary Search  

 1 class Solution(object):
 2     def mySqrt(self, x):
 3         """
 4         :type x: int
 5         :rtype: int
 6         """
 7         l = 0
 8         r = x
 9         
10         while l <= r:
11             mid = (l+r)//2
12             if mid*mid < x:
13                 l = mid + 1 
14             elif mid*mid > x:
15                 r = mid - 1
16             else:
17                 return mid
18         return r

 

posted @ 2017-01-07 11:53  lettuan  阅读(97)  评论(0编辑  收藏  举报