LeetCode-69 Sqrt(x)
Implement int sqrt(int x)
.
Compute and return the square root of x.
思路:二分法。
比较要留意的是right left 的处理。
public class Solution {
public int mySqrt(int x) {
if (x == 0) {
return 0;
}
int left = 1;
int right = x;
while(left <= right){
int mid = (left+right)/2;
if (mid == x/mid) {
return mid;
}
if (mid > x/mid) {
right = mid-1;//★
}else {
left = mid+1;//★
}
}
return right;
}
}