[leetcode]Sqrt(x) @ Python
2014-06-08 10:19
351 查看
原题地址:https://oj.leetcode.com/problems/sqrtx/
题意:
Implement
Compute and return the square root of x.
解题思路:实现开平方函数。这里要注意的一点是返回的时一个整数。通过这一点我们可以看出,很有可能是使用二分查找来解决问题的。这里要注意折半查找起点和终点的设置。起点i=1;终点j=x/2+1;因为在(x/2+1)^2 > x,所以我们将折半查找的终点设为x/2+1。
代码:
题意:
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
相关文章推荐
- [LeetCode]题解(python):069-Sqrt(x)
- [leetcode:python]69.Sqrt(x)
- LeetCode 69 — Sqrt(x)(C++ Java Python)
- [Leetcode]69. Sqrt(x)解析@Python
- LeetCode---69. Sqrt(x)---Python实现
- LeetCode--Sqrt(x)Python
- [Leetcode]@python 69. Sqrt(x)
- 【Leetcode】【python】Sqrt(x)
- [Leetcode By Python]69. Sqrt(x)
- 【LeetCode 69】Sqrt(x) (Python)
- leetcode 日经贴,python code -Sqrt(x)
- 【leetcode】69. Sqrt(x)(Python & C++)
- LeetCode-69-Sqrt(x) Python要用math.sqrt()
- [LeetCode]Sqrt(x)@python
- 【LeetCode with Python】 Best Time to Buy and Sell Stock II
- 【LeetCode with Python】 Merge Two Sorted Lists
- 【LeetCode with Python】 Remove Duplicates from Sorted Array
- 【LeetCode with Python】 Binary Tree Preorder Traversal
- 【LeetCode with Python】 Maximum Depth of Binary Tree
- 【LeetCode with Python】 Single Number