Implement
int sqrt(int x)
.
Compute and return the square root of x.
Solution:
Method 1: Binary Search
Implementation is straightforward.
One tricky part is we use mid < x / mid instead of mid * mid < x just in case of Integer overflow.
Code:
public class Solution { public int mySqrt(int x) { if (x == 0) { return 0; } int start = 1; int end = x; while (start + 1 < end) { int mid = start + (end - start) / 2; if (mid < x / mid) { start = mid; } else { end = mid; } } if (end <= x / end) { return end; } return start; } }
Method 2: Newton's Method