Implementint sqrt(int x)
.
Compute and return the square rootX.
public class Solution { public int sqrt(int x) { if(x < 0) return -1;if(x == 0) return 0;//binary search methodlong high = x / 2 + 1;long low = 0;while(low <= high) {long mid = low + (high - low) / 2;long approximateSquare = mid * mid;if(approximateSquare == x)return (int) mid;if(approximateSquare < x) //too smalllow = mid + 1;else //too largehigh = mid - 1;}return (int) high; }}
Newton Iteration Method (X _ {I + 1} = x_ I-F (x_ I)/f ^ '(x_ I). Where f ^' (x_ I) = 2x_ I in this problem.
Therefore, X _ {I + 1} = x_ I-(x_ I ^ 2-x)/2x_ I = (x_ I + x/X_ I)/2. the algorithm converges to the root, so the termination condition of the loop is X _ {I }== X {I + 1}
public class Solution { public int sqrt(int x) { if(x < 0) return -1;if(x == 0) return 0;double last = 0;double iter = 1;while(last != iter){ //termination condition. the algorithm converges to the rootlast = iter;iter = (iter + x / iter) / 2;}return (int) iter; }}