0%

69.x的平方根

69. x 的平方根

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int mySqrt(int x){
long long temp;
long long left = 1;
long long right = x;
long long middle;
if (x==0)temp=0;
else if (x==1) temp=1;
else if(x!=0&&x!=1){
while(left<=right){
middle=(left+right)/2;
if(middle<=x/middle){
temp=middle;
left=middle+1;
}
else if(middle>x/middle){
right=middle-1;
}
}

}
return temp;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<iostream>
#include<vector>
using namespace std;
int main(){
int temp;
int n;
cin>>n;
// vector<int> x;
// for(int i=0;i<n;i++)
// {
// x.push_back(i);
// }
int left=1;
int right=n;
int middle;
// int target=2;

while(left<=right){
middle=(left+right)/2;
if(middle>n/middle){
right=middle-1;
}
else if(middle<=n/middle){ //middle^2<n
temp=middle; //因为2^2<8<2^3 所以直接取这边的middle
left=middle+1;
}

}
cout<<temp;


return 0;
}
-------------本文结束感谢您的阅读-------------
老板你好,讨口饭吃