Sqrt(x)
Implement int sqrt(int x)
.
Compute and return the square root of x.
思路:
使用二分。为了减少搜索范围,将上界定位最大的整数的开方,也避免了整数越界的情况。另外在第9行分别先除2再相加,也是避免越界。
代码:
1 int border(int a){ 2 if(a < 46341) 3 return a; 4 return 46341; 5 } 6 int sqrt(int left, int right, int x){ 7 if(left == right) 8 return left-1; 9 int middle = border(left/2 + right/2); 10 double t = middle*middle; 11 if(t < x){ 12 return sqrt(middle+1, right, x); 13 } 14 else if(t > x){ 15 return sqrt(left, middle, x); 16 } 17 else 18 return middle; 19 } 20 int sqrt(int x) { 21 // IMPORTANT: Please reset any member data you declared, as 22 // the same Solution instance will be reused for each test case. 23 if(x == 0 || x == 1) 24 return x; 25 return sqrt(1, border(x), x); 26 }