您的位置:首页 > 编程语言 > Python开发

[leetcode]Sqrt(x) @ Python

2014-06-08 10:19 351 查看
原题地址: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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: