-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path69-sqrtx.cpp
57 lines (51 loc) · 1.38 KB
/
69-sqrtx.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
49
50
51
52
53
54
55
56
57
#include <iomanip>
#include <chrono>
#include <iostream>
using namespace std;
class Solution {
public:
// first attempt: time limit exceeded
/* int mySqrt(int x) {
if(x==1) return 1; // corner case;
long long y{x/2};
while(y*y>x) // all the other cases
--y;
return y;
} */
// second attemp with binary approach
int mySqrt(int x) {
if(x==1) return 1; // corner case;
long long y{x/2};
while(y*y>x)
y/=2;
while((y+1)*(y+1)<=x)
++y;
return y;
}
// LeetCode most performing solution
int mySqrt2(int x) {
unsigned long int mid,s=0,e=x,ans;
while(s<=e){
mid=(s+e)/2;
if(mid*mid>x){
e=mid-1;
}
else{
ans=mid;
s=mid+1;
}
}
return ans;
}
};
int main() {
Solution solution;
int x;
cin >> x;
auto t1 = chrono::high_resolution_clock::now();
cout << solution.mySqrt(x) << '\n';
auto t2 = chrono::high_resolution_clock::now();
chrono::duration<double, milli> ms_double = t2 - t1;
cout << setprecision(17) << ms_double.count() << " ms\n";
return 0;
}