-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqrt.cpp
48 lines (46 loc) · 860 Bytes
/
sqrt.cpp
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include<iostream>
#include<vector>
#include<algorithm>
class Solution {
public:
int mySqrt(int x) {
for(long int i=0; i<=x+1;i++){
if(i*i>x)
return i-1;
}
return -1;
}
int search(int left, int right, int x){
int tmp = (left+right)/2;
if(left + 1== right){
if(tmp*tmp == x)
return tmp;
else if(tmp*tmp>x){
left = left;
right = tmp;
}
else{
left = tmp;
right = right;
}
tmp = search(left, right, x);
}
return tmp;
}
int mySqrtb(int x) {
int left = 0;
int right = x;
if(x == 1)
return 1;
return search(left, right, x);
}
};
int main(){
Solution s;
std::cout<<"input value: ";
int a;
std::cin>>a;
std::cout<<"result: ";
std::cout<<s.mySqrtb(a)<<std::endl;
return 1;
}