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:
http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html