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

【小熊刷题】sqrt(x) <Leetcode 69 Java>

2015-09-04 10:05 477 查看

Question

Implement int sqrt(int x).

Compute and return the square root of x.

**Difficulty: Medium

https://leetcode.com/problems/sqrtx/

Solution - Binary Search

O(logN)

public class Solution {
public int mySqrt(int x) {
int L = 1; int R = x/2;
if(x < 2) return x;
while(L <= R){
int M = (L+R)/2;
//using divide to avoid overflow
if(x / M == M) return M;
else if(x / M > M) L = M + 1;
else R = M - 1;
}
return R;
}
}


Another way is using Newton’s iteration methods: x(i+1) = (x(i) + n/x(i)) / 2 See more details in this link:

/article/6999389.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: