69. Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

Example

sqrt(3) = 1

sqrt(4) = 2

sqrt(5) = 2

sqrt(10) = 3

 1 class Solution {
 2     public int mySqrt(int x) {
 3         long start = 0, end = x;
 4 
 5         while (start <= end) {
 6             long mid = start + (end - start) / 2;
 7             if (mid * mid == x) {
 8                 return (int) mid;
 9             } else if (mid * mid < x) {
10                 start = mid + 1;
11             } else {
12                 end = mid - 1;
13             }
14         }
15         return (int) end;  // we are looking for lower end.
16     }
17 }

另一个版本: double sqrt(double x, int precision)

 1 double sqrt(double x, int k) {
 2         if (x < 0) throw new IllegalArgumentException("The input " + x + " is less than 0.");
 3         if (x == 0) return 0;
 4         double start = 0; 
 5         double end = x;
 6         while (start <= end) {
 7             double mid = (end - start) / 2 + start;
 8             double result = mid * mid;
 9             if (isWithinLimit(result, x, k)) {
10                 return mid;
11             } else if (result > x) {
12                 end = mid;
13             } else {
14                 start = mid;
15             }
16         }
17         return -1;
18     }
19     
20     boolean isWithinLimit(double v1, double v2, int k) {
21         double precision = 1.0 / Math.pow(10, k);
22         if (Math.abs(v1 - v2) <= precision) {
23             return true;
24         }
25         return false;
26     }

 还有就是用牛顿法:https://blog.csdn.net/brianleelxt/article/details/81152668

 1 public static double sqr(double c) {
 2         if (c < 0) {
 3             return Double.NaN;
 4         }
 5         double err = 1e-15;
 6         double x = c;
 7         while (Math.abs(x - c / x) > err * x) {
 8             x = (c / x + x) / 2.0;
 9         }
10         return x;
11     }
posted @ 2016-07-10 12:29  北叶青藤  阅读(197)  评论(0编辑  收藏  举报