Sqrt(x)
Thoughts
Code
/*
* @lc app=leetcode id=69 lang=cpp
*
* [69] Sqrt(x)
*/
class Solution {
public:
int mySqrt(int x) {
int start = 1, end = min(x / 2, 46340);
while (start < end) {
int mid = start + (end - start) / 2;
if (mid * mid < x) start = mid + 1;
else end = mid;
}
return start * start > x ? start - 1 : start;
}
};
class Solution {
public int mySqrt(int x) {
long r = x;
while (r * r > x) {
r = (r + x / r) / 2;
}
return (int) r;
}
}Analysis
Last updated