[leetcode] 69. Sqrt(x)
题目链接:https://leetcode.com/problems/sqrtx/
Implement int sqrt(int x).
Compute and return the square root of x.
思路
二分查找,每次看中间的数平方是不是和当前数相等.
class Solution {
public:
int mySqrt(int x) {
if(x <= 0) return 0;
long left = 1, right = x;
while(left <= right){
long mid = (left + right) / 2;
if(mid * mid > x) right = mid - 1;
else left = mid + 1;
}
return left - 1;
}
};