-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqrt.cpp
More file actions
32 lines (31 loc) · 728 Bytes
/
Copy pathsqrt.cpp
File metadata and controls
32 lines (31 loc) · 728 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
class Solution {
public:
/**
* @param x: An integer
* @return: The sqrt of x
*/
int sqrt(int x) {
// write your code here
if (x <= 1) {
return 0;
}
int start = 1;
int end = x;
int mid;
while (start + 1 < end) {
mid = start + (end - start) / 2;
// bug: mid * mid exceed the limit of INT
if (x / mid == mid) {
return mid;
} else if (mid < x / mid ) {
start = mid;
} else if (mid > x / mid) {
end = mid;
}
}
if (end * end == x) {
return end;
}
return start;
}
};