forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSqrt(x).cpp
35 lines (34 loc) · 838 Bytes
/
Sqrt(x).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
class Solution {
public:
int sqrt(int x) {
long long high = x;
long long low = 0;
if (x <= 0) {return 0;}
if (x == 1) {return 1;}
while (high - low > 1) {
long long mid = low + (high - low) / 2;
if (mid * mid <= x){ low = mid; }
else { high = mid; }
}
return low;
}
};
// no hassle of overflow
class Solution {
public:
int sqrt(int x) {
if (x == 0) return 0;
int start = 1, end = x;
int result;
while (start <= end) {
int mid = start + (end - start) / 2;
if (mid <= x / mid) {
start = mid + 1;
result = mid;
} else {
end = mid - 1;
}
}
return result;
}
};