69. Sqrt(x)

binary search method 
class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x<=1: return x
        left,right=1,x/2
        while True: 
            mid=(left+right)/2 
            if mid*mid>x:
                right=mid-1
            else: 
                if (mid+1)*(mid+1)>x:return mid
                left=mid+1 
newton integer method 
class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        a=x
        while a*a>x:
            a=(a+x/a)/2
        return a
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Implement int sqrt(int x). Compute and return the square ...
    Jeanz阅读 258评论 0 0
  • 题目 Implement int sqrt(int x). Compute and return the squa...
    Al73r阅读 153评论 0 0
  • Description: Implement int sqrt(int x). Compute and retur...
    Icytail阅读 301评论 0 0
  • 一开始我的想法是直接相乘到大于X取此时的count-1就好了,事实证明这个方法的效率比较低,我的算法直接排到了倒数...
    namelessEcho阅读 422评论 0 0
  • Implementint sqrt(int x).Compute and return the square ro...
    juexin阅读 257评论 0 0

友情链接更多精彩内容