Sqrt(x)
https://leetcode.com/problems/sqrtx/
Simplest Approach:
class Solution {
public:
int mySqrt(int x) {
long long int y=0;
while(y*y<=x)
{
y++;
}
return y-1;
}
};
optimal using binary search:
class Solution {
public:
int mySqrt(int x) {
long long int s=0,e=INT_MAX,ans=0;
while(s<=e)
{
long long int m=s+(e-s)/2;
if(m*m <=x)
{
ans=m;
s=m+1;
}
else{
e=m-1;
}
}
return ans;
}
};
Comments
Post a Comment