题目链接
解题思路
二分法
- 题目要求的是保留整数部分,因此二分法的退出条件是 r i g h t − l e f t < 1 right - left < 1 right−left<1
AC代码
class Solution {
public int mySqrt(int x) {
if (x == 1)
return 1;
int left = 0;
int right = x;
while (right - left > 1) {
int middle = left + (right - left) / 2;
if (x / middle < middle) {
right = middle;
} else
left = middle;
}
return left;
}
}