Title:
Implement int sqrt(int x)
.
Compute and return the square root of X.
Test Instructions:
Implement the root function.
Algorithm Analysis:
The problem of this mathematical operation, just start the first time when the brush to tell the truth I was cheating AC. After a lot of senior blog said this topic interview is very common, suggest or think about it well.
Reference is made to HTTP://PISXW.COM/ALGORITHM/SQRT (x). html
The problem uses another method that is often used in numerical values: the dichotomy. The basic idea is similar to binary search, the requirement is to know the scope of the results, to set the left and right boundaries, and then every time you cut off the half of the conditions, until the left and right to meet.
The more typical numerical processing problems are Divide two integers,Pow (X,n), and so on, in fact, the method is similar, generally is the dichotomy or 2-based processing method.
AC Code:
public class Solution {public int sqrt (int x) { ////know the scope of the result, you can use the dichotomy if (x<0) return-1; if (x==0) return 0; int left=1; int right=x/2+1; while (Left<=right) { int m= (left+right)/2; if (m<=x/m && (m+1) >x/(m+1)) return m; if (m>x/m) right=m-1; else left=m+1; } return 0;} }
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] SQRT (x)