We should keep in mind so never let the integer value overranged or overstacked.
Here are the trick, instead of comparing the square of a interger with the target value, we can compare the integer value I With the quotient x/i;
if (i > x/i) high = i-1; if (I < x/i) low = i +1, the condition of the and is loop are low < high. Thus when the loop is ends, low = high. There is and results, one is the low point to the integer which was the sqrt (x), the other is low = sqrt (x) +1. We need to check the "cases" in the end.
Code:
public class Solution {public int mysqrt (int x) { if (x<0) return-1; if (x = = 0) return 0; if (x = = 1) return 1; int low = 1, high = x; while (Low < high) { int mid = low+ (high-low)/2; int quotient = X/mid; if (quotient = = mid) return mid; else if (Mid > Quotient) {high = mid-1; } else{Low = mid + 1; } } int quotient = X/low; if (Low > Quotient) return low-1; return low; }}
Newton ' s method to get square root:
Code:
Public int mysqrt (int x) { ifreturn 0; long i = x; while (i > x/ i) = (i + x/i)/2; return (int) i;}
Jan 19-sqrt (x); Math; Binary Search;