-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy path69_Sqrt_x.cpp
48 lines (45 loc) · 893 Bytes
/
69_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
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* @Author: [email protected]
* @Last Modified time: 2016-07-01 20:42:32
*/
class Solution {
public:
int mySqrt(int x) {
if(x < 2){
return x;
}
int low = 0, high = x;
while(low <= high){
int mid = low + (high - low) / 2;
// mid * mid will overflow when mid > sqrt(INT_MAX)
if(x / mid >= mid && x / (mid+1) < (mid+1)){
return mid;
}
else if(x / mid < mid){
high = mid - 1;
}
else{
low = mid + 1;
}
}
return -1; // Can'e be reached!
}
};
class Solution_2{
public:
int mySqrt(int x) {
// Newton iterative method
long ans = x;
while(ans * ans > x){
ans = (ans + x/ans) / 2;
}
return ans;
}
};
/*
0
1
15
90
1010
*/