目录
一、题目
二、暴力求解
三、二分查找(改进)
一、题目
https://leetcode.cn/problems/sqrtx/description/
二、暴力求解
1.溢出问题
2.x为1
class Solution {
public:
int mySqrt(int x) {
if(x== 1)
return 1;
long long i=0;
for(i;i<=x/2;i++)
{
if(i*i>x)
{
break;
}
}
return i-1;
}
};
三、二分查找(改进)
class Solution {
public:
int mySqrt(int x)
{
if(x== 0)
return 0;
if(x== 1||x==2)
return 1;
long long left=0;
long long right = x/2;
long long mid = (right+left)/2;
while(left<=right)
{
if(mid*mid<x)
{
left = mid+1;
mid = (left+right)/2;
}
else if(mid*mid>x)
{
right = mid-1;
mid = (left+right)/2;
}
else
{
return mid;
}
}
return right;
}
};