leetcode-69. x 的平方根
题目:
代码:
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int mySqrt(int x) {
//方法一,数学公式替换 x^1/2=(e^lnx)^1/2=e^1/2^lnx
// if(x==0){
// return 0;
// }
// int ans=exp(0.5*log(x));
// return (long long)(ans+1)*(ans+1)<=x?ans+1:ans;
//方法二,二分查找 k^2<=x l=0,r=x,m=(l+r)/2
int l=0,r=x,ans=0;
int m;
while(l<=r){
m=(l+r)/2;
if((long long)m*m<=x){
ans=m;
l=m+1;
}else{
r=m-1;
}
}
return ans;
}
int main(){
int x,res;
cin>>x;
res=mySqrt(x);
cout<<res;
return 0;
}