/*
时间复杂度 O(lon(n)) 空间 O(1)
*/
class Solution {
public:
int mySqrt(int x) {
int left = 1;
int right = x/2;
int mid ;
int last_mid ;
if(x < 2)
{
return x;
}
while(left <= right)
{
mid = (left + right)/2;
if(x/mid < mid) //不要用 mid * mid > x
{
right = mid-1;
}
else if(x/mid > mid)
{
left = mid+1;
last_mid = mid;
}
else
{
return mid;
}
}
return last_mid;
}
};
LintCode 炼码 - ChatGPT!更高效的学习体验!
题解:九章算法 - 帮助更多程序员找到好工作,硅谷顶尖IT企业工程师实时在线授课为你传授面试技巧
九章算法 - 帮助更多程序员找到好工作,硅谷顶尖IT企业工程师实时在线授课为你传授面试技巧
浮点数在计算机中的表示_misterliwei的博客-CSDN博客
class Solution {
public:
/**
* @param x: An integer
* @return: The sqrt of x
*/
int sqrt(int x) {
// write your code here
int left = 1;
int right = x;
while (left + 1 < right) {
int mid = left + (right-left)/2;
if (x/mid == mid) {
return mid;
} else if (x/mid < mid) {
right = mid;
} else {
left = mid;
}
}
if (right*right == x) {
return right;
}
return left;
}
};