java:
//用/防止溢出
class Solution {
public int mySqrt(int x) {
int left = 1, right = x;
while (left < right) {
int middle = left + (right - left) / 2;
if (middle < (x / middle)) {
left = ++middle;
}
else if (middle > (x / middle)) {
right = --middle;
}
else {
return middle;
}
}//注!!等于得情况需要考虑
return left <= (x / left) ? left : left - 1;
}
}
//long防止溢出
class Solution {
public int mySqrt(int x) {
long left = 0;
long right = (long)x;
while (left < right) {
long middle = left + (right - left) / 2;
if (squre(middle) < x) {
left = ++middle;
}
else if (squre(middle) > x) {
right = --middle;
}
else {
return (int)middle;
}
}
return squre(left) > (long)x ? (int)(left - 1) : (int)(left);
}
public long squre(long tem) {
return tem * tem;
}
}
class Solution {
public:
int mySqrt(int x) {
int left = 1, right = x;//0的情况也满足,从1开始就可以
while (left < right) {
int middle = left + (right - left) / 2;
if (middle < x / middle) {//用除防止溢出
left = middle + 1;
}
else if (middle > x / middle) {
right = middle - 1;
}
else {
return middle;
}
}
return left > x / left ? left - 1 : left;//最后判断left的位置得到最终结果
}
};