[leetcode]Sqrt(x)
2014-08-08 00:05
357 查看
Sqrt(x)
Implement
int sqrt(int x).
Compute and return the square root of x.
【注意】:
1. 本题int类型可能会溢出,因此不能用乘法运算,应尽量用除法。
2. 绝大多数数字都不是可开方的,该如何得到比较近的结果呢?
算法思路:
思路1:顺序遍历肯定不需要试了,二分查找比较靠谱。二分法在数值计算中非常常见,需要熟练掌握。
代码如下:
public class Solution { public int sqrt(int x) { if(x <= 1) return x == 0 ? 0 : x; int l = 1, r = x /2 + 1 ; while(l <= r){ int mid = (l + r) / 2; if(mid <= x / mid && (mid + 1) > x / (mid + 1)){ return mid;//这里用的很巧妙 }else if(mid > x / mid){ r = mid - 1; }else{ l = mid + 1; } } return 0; } }
思路2:牛顿迭代法;比较高大上,详细分析过程请戳这里。
代码如下:
public int sqrt(int x) { if (x == 0) return 0; double lastY = 0; double y = 1; while (y != lastY) { lastY = y; y = (y + x / y) / 2; } return (int)(y); }
这道题出的很好
相关文章推荐
- leetcode 69. Sqrt(x)
- [LeetCode] Sqrt(x)
- [leetcode] Sqrt(x)
- leetcode :Binary Search:Sqrt(x)(069)
- LeetCode - 50/69/367/633 - Pow(x, n)、Sqrt(x)
- leetcode 69 sqrt(x)
- [Leetcode]#69 Sqrt(x)
- LeetCode Sqrt(x) 整数平方根 java
- leetCode力扣之Sqrt(x)
- LeetCode 69. Sqrt(x)
- leetcode sqrt
- LeetCOde No.69 Sqrt(x)
- LeetCode 69.Sqrt(x)
- [Leetcode] Sqrt(x)
- leetcode 69. Sqrt(x)
- 【LeetCode 69】Sqrt(x)
- LeetCode 69 Sqrt(x)
- Leetcode 69 Sqrt(x)
- [LeetCode]sqrt(int x)解题报告之二分查找
- [leetcode] 69 Sqrt(x)