Sqrt(x)
Description
Implement intsqrt(int x)
.
Compute and return the square root ofx.
Example
sqrt(3) = 1
sqrt(4) = 2
sqrt(5) = 2
sqrt(10) = 3
Challenge
O(log(x))
Related problems
Sqrt(x) II
Medium Pow(x, n)
Easy First Position of Target
Implementation
Link: http://lintcode.com/en/problem/sqrtx/
class Solution {
public:
/**
* @param x: An integer
* @return: The sqrt of x
*/
int sqrt(int x) {
// write your code here
// Note:
if (x <= 1 ) {
return x;
}
int start = 1;
int end = x/2;
while (start + 1 < end) {
int mid = start + (end -start ) /2;
if(mid == x / mid) {
return mid;
} else if (mid < (x /mid)) {
start = mid;
} else {
end = mid;
}
}
return start;
}
int sqrtVer2(int x) {
// write your code here
if(x <= 1) return x;
long start = 0, end = x / 2;
while(start + 1 < end) {
long mid = start + (end - start) / 2;
if(mid * mid == x) {
return mid;
} else if(mid * mid < x) {
start = mid;
} else {
end = mid;
}
}
return start;
}
};