Implement int sqrt(int x)
.
Compute and return the square root of X.
Has you met this question in a real interview?Yes
Example
sqrt (3) = 1
sqrt (4) = 2
sqrt (5) = 2
sqrt (10) = 3
1 classSolution {2 /**3 * @param x:an integer4 * @return: The sqrt of x5 */6 Public intsqrtintx) {7 LongStart =0;8 LongEnd =x;9 Ten while(Start <=end) { One LongMID = start + (End-start)/2; A if(Mid * mid = =x) { - return(int) mid; -}Else if(Mid * Mid <x) { theStart = mid +1; -}Else { -End = Mid-1; - } + } - return(int) (Start-1); We are looking for lower end. + } A}
Or we can do it another.
1 classSolution {2 /**3 * @param x:an integer4 * @return: The sqrt of x5 */6 Public intsqrtintx) {7 LongStart =0;8 LongEnd =x;9 Ten while(Start <=end) { One LongMID = start + (End-start)/2; A if(Mid * mid = =x) { - return(int) mid; -}Else if(Mid * Mid < x && (mid +1) * (Mid +1) >x) { the return(int) mid; -}Else if(Mid * Mid <x) { -Start = mid +1; -}Else { +End = Mid-1; - } + } A return-1; at } -}
SQRT (x)