LeetCode:Sqrt(x)
2015-01-07 19:02
281 查看
题目描述:
Implement
Compute and return the square root of x.
思路分析:采用二分查找的思想。当未找到mid=x/mid时,若mid>x/mid,则表示mid-1为平方值最接近但不超过x的值,即结果为mid-1。若mid<x/mid,则表示结果为mid为平方值最接近但不超过x的值,即结果为mid。
代码:
Implement
int sqrt(int x).
Compute and return the square root of x.
思路分析:采用二分查找的思想。当未找到mid=x/mid时,若mid>x/mid,则表示mid-1为平方值最接近但不超过x的值,即结果为mid-1。若mid<x/mid,则表示结果为mid为平方值最接近但不超过x的值,即结果为mid。
代码:
if(x == 0 || x == 1) return x; int start = 0; int end = x; int result; while(start <= end) { int mid = (start+end)/2; if(mid == x/mid) return mid; else if(mid > x/mid) { end = mid - 1; result = mid - 1; } else { start = mid + 1; result = mid; } } return result; }
相关文章推荐
- 数据结构与算法[LeetCode]——sqrt(x)
- LeetCode: Sqrt(x)
- [Leetcode] sqrt 开根号
- LeetCode:Sqrt(x)
- Sqrt(x) -- leetcode
- LeetCode之Sqrt(x)
- [leetcode]Sqrt(x)
- (Java)LeetCode-69. Sqrt(x)
- leetcode之sqrt
- LeetCode - Sqrt(x)
- LeetCode(69)Sqrt
- 【LeetCode】69. Sqrt(x)
- LeetCode 69 — Sqrt(x)(C++ Java Python)
- leetcode: sqrt
- leetcode 69. Sqrt(x)
- LeetCode 83 Sqrt(x)
- LeetCode-69. Sqrt(x)
- LeetCode | Sqrt(x)
- [leetcode.com]算法题目 - Sqrt(x)
- leetcode第一刷_Sqrt(x)