lettcode:二分法sqrt(x)

来源:互联网 发布:java反序列化代码 编辑:程序博客网 时间:2024/06/02 07:02
题目:

Implementint sqrt(int x).

Compute and return the square root of x.

代码如下:

public class Solution {
    public int sqrt(int x) {
         if(x<=1)
             return x;
        int begin=1;
        int end=x;
        int mid=0;
        while(begin<=end){
            mid=begin+(end-begin)/2;
            //如果写成mid*mid==x,会溢出
            if(mid==x/mid){
                return mid;
            }else if(mid<x/mid){
                begin=mid+1;
            }else{
                end=mid-1;
            }
        }
      //结果返回end,end一定小于begin
        return end;
    }
}

原创粉丝点击