forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain2.cpp
More file actions
42 lines (31 loc) · 717 Bytes
/
main2.cpp
File metadata and controls
42 lines (31 loc) · 717 Bytes
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
/// Source : https://leetcode.com/problems/sqrtx/description/
/// Author : liuyubobobo
/// Time : 2019-04-03
#include <iostream>
using namespace std;
/// Binary Search
/// Using double first
///
/// Time Complexity: O(log(MAX_INT) * precision)
/// Space Complexity: O(1)
class Solution {
private:
double e = 1e-6;
public:
int mySqrt(int x) {
double l = 0.0, r = INT_MAX;
while(r - l >= e){
double mid = (l + r) / 2;
if(mid * mid <= x)
l = mid;
else
r = mid;
}
return (int)r;
}
};
int main() {
cout << Solution().mySqrt(4) << endl;
cout << Solution().mySqrt(8) << endl;
return 0;
}