Implement int
sqrt(int x)
.
Compute and return the square root of x.
二分法:
class Solution {
public:
int sqrt(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (x<=0)
return 0;
int start = 1;
int end = x;
long mid = (start+end)/2;
while (start <= end){
if (x/mid == mid)
return mid;
if (x/mid < mid)
end = mid-1;
if (x/mid > mid)
start = mid+1;
mid = (start+end)/2;
}
return mid;
}
};
不同的系统不一样啊…………亲 超出界限用long long
2。 开始用的 (mid*mid == x) 明显少考虑了很多情况,如 sqrt(5)=2, 而2*2 = 4