x的平方根

来源:互联网 发布:nginx 模块开发 编辑:程序博客网 时间:2024/04/27 16:29

问题描述:
实现 int sqrt(int x) 函数,计算并返回 x 的平方根。
样例:
sqrt(3) = 1

sqrt(4) = 2

sqrt(5) = 2

sqrt(10) = 3
代码:

class Solution {    /**     * @param x: An integer     * @return: The sqrt of x     */    public int sqrt(int x) {        // write your code here        if(x<2){            return x;        }        int low=1;        int high=x/2;        int mid=0;        int lastmid=0;        while(low<=high){            mid=(low+high)/2;            if(x/mid>mid){                low=mid+1;                lastmid=mid;            }else if(x/mid<mid){                high=mid-1;            }else{                return mid;            }        }        return lastmid;    }}
0 0