Implement intsqrt(int x)
.
Compute and return the square root of x.
Example
sqrt(3) = 1
sqrt(4) = 2
sqrt(5) = 2
sqrt(10) = 3
class Solution {
/**
* @param x: An integer
* @return: The sqrt of x
*/
public int sqrt(int x) {
if (x == 1) {
return 1;
}
long i = 0;
long j = x / 2 + 1;
while (i <= j) {
long mid = (i + j) / 2;
long sq = mid * mid;
if (sq == x) {
return (int) mid;
} else if (sq < x) {
i = mid + 1;
} else {
j = mid - 1;
}
}
return (int)j;
}
}