原题网址:http://www.lintcode.com/zh-cn/problem/sqrtx/
实现 int sqrt(int x) 函数,计算并返回 x 的平方根。
int sqrt(int x)
sqrt(3) = 1
sqrt(4) = 2
sqrt(5) = 2
sqrt(10) = 3
O(log(x))
1 #include <iostream> 2 #include <vector> 3 #include <math.h> 4 #include <string> 5 #include <algorithm> 6 using namespace std; 7 8 int sqrt(int x) 9 { 10 if (x<0) 11 { 12 return -1; 13 } 14 15 long long low=0,high=x,mid=(low+high)/2; //为何用int会出错?; 16 while (low<=high) //mid*mid有可能超出int范围被截断,小于x,若(mid+1)*(mid+1)被截断后仍小于x,返回错误结果; 17 { 18 if (mid*mid==x) 19 { 20 return mid; 21 } 22 else if (mid*mid>x) 23 { 24 high=mid-1; 25 } 26 else 27 { 28 if ((mid+1)*(mid+1)>x) 29 { 30 return mid; 31 } 32 else 33 low=mid+1; 34 } 35 mid=(low+high)/2; 36 } 37 38 }
参考:
1 https://blog.csdn.net/gao1440156051/article/details/49766733
2 http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html
3 https://www.cnblogs.com/libaoquan/p/7224644.html