forked from rost0413/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sqrt.cpp
52 lines (46 loc) · 915 Bytes
/
Sqrt.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
/*
Author: Weixian Zhou, ideazwx@gmail.com
Date: Jul 23, 2012
Problem: Sqrt(x)
Difficulty: medium
Source: http://www.leetcode.com/onlinejudge
Notes:
Implement int sqrt(int x).
Compute and return the square root of x.
Solution:
Binary search. Return the lower bound.
*/
#include <vector>
#include <set>
#include <climits>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstring>
#include <list>
using namespace std;
class Solution {
public:
int sqrt(int x) {
int low = 0, high = x, root;
while (low <= high) {
int mid = low + (high - low) / 2; // avoid overflow
if (mid > 46340) { // 46340^2 ~= INT_MAX
high = mid - 1;
continue;
}
int multi = mid * mid;
if (multi == x) {
return mid;
}
if (multi > x) {
high = mid - 1;
} else {
low = mid + 1;
root = mid;
}
}
return root;
}
};