实现函数 int sqrt(int x).
计算并返回x的平方根
import java.util.*;
public class Solution {
/**
*
* @param x int整型
* @return int整型
*/
public int sqrt (int x) {
// write code here
if(x == 0) {
return 0;
}
int left = 1, right = x;
int res = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if ((long) mid * mid <= x){
res = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}
return res;
}
}