LeetCode-Sqrt(x)
问题:实现 int sqrt(int x).
这里给出两种实现方法:一是二分搜索,二是牛顿迭代法。
- 二分搜索
1 int sqrt(int x) { 2 long long i = 0; 3 long long j = x / 2 + 1; 4 while (i <= j) 5 { 6 long long mid = (i + j) / 2; 7 long long sq = mid * mid; 8 if (sq == x) return mid; 9 else if (sq < x) i = mid + 1; 10 else j = mid - 1; 11 } 12 return j; 13 }
- 牛顿迭代法
1 int sqrt(int x) { 2 if (x == 0) return 0; 3 double last = 0; 4 double res = 1; 5 while (res != last) 6 { 7 last = res; 8 res = (res + x / res) / 2; 9 } 10 return int(res); 11 }
- 此外,如果返回值不是整型
1 double sqrt(double x) { 2 if (x == 0) return 0; 3 double last = 0.0; 4 double res = 1.0; 5 while (res != last) 6 { 7 last = res; 8 res = (res + x / res) / 2; 9 } 10 return res; 11 }
参考:http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html