[leetcode]Sqrt(x) @ Python

原题地址:https://oj.leetcode.com/problems/sqrtx/

题意:

Implement int sqrt(int x).

Compute and return the square root of x.

解题思路:实现开平方函数。这里要注意的一点是返回的时一个整数。通过这一点我们可以看出,很有可能是使用二分查找来解决问题的。这里要注意折半查找起点和终点的设置。起点i=1;终点j=x/2+1;因为在(x/2+1)^2 > x,所以我们将折半查找的终点设为x/2+1。

代码:

class Solution:
    # @param x, an integer
    # @return an integer
    def sqrt(self, x):
        if x == 0:
            return 0
        i = 1; j = x / 2 + 1
        while( i <= j ):
            center = ( i + j ) / 2
            if center ** 2 == x:
                return center
            elif center ** 2 > x:
                j = center - 1
            else:
                i = center + 1
        return j

 

    原文作者:南郭子綦
    原文地址: https://www.cnblogs.com/zuoyuan/p/3775852.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞