[leetcode]Sqrt(x) @ Python

时间:2014-06-08 21:04:38   收藏:0   阅读:329

原题地址: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。

代码:

bubuko.com,布布扣
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
bubuko.com,布布扣

 

[leetcode]Sqrt(x) @ Python,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!