Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

参考:http://standalone.iteye.com/blog/1847368

参考的是一个用二分查找实现的,这道题还可以用什么牛顿法之类的

如果middle * middle > x在左半部分查找,如果middle * middle < x在有半部分查找。初始状态low = 0, high = x

 1 public class Solution {
 2     public int sqrt(int x) {
 3        double low = 0;
 4        double precision = 0.000000001;
 5        double high = x;
 6        while((high - low ) >precision){
 7            double middle = (low + high) / 2;
 8            if(x > middle * middle){
 9                low = middle;
10            }
11            if(x < middle * middle){
12                high = middle;
13            }
14            if(x == middle * middle){
15                return (int)Math.floor(middle);
16            }
17        }//while
18        return (int)Math.floor(high);
19     }
20 }
原文地址:https://www.cnblogs.com/luckygxf/p/4219054.html