leetCode练习(69)

来源:互联网 发布:中国阶级 知乎 编辑:程序博客网 时间:2024/06/07 22:32

题目:Sqrt(x)

难度:medium

问题描述:

Implement int sqrt(int x).

Compute and return the square root of x.

Subscribe to see which companies asked this question

解题思路:

求平方根。首先想到从1到n以此检测I*I是否大于x。但若x很大,需要遍历很多项,速度慢、因此想到二分搜索来计算。

确定了计算方法,这道题解决了一小半。真正的难点在于边界问题。如果x为int的极大左右,那么二分的起点 (x/2)的平方已经超出整数界限,需要主要超限问题。

具体代码如下:

public static int mySqrt(int x) {int head=1;int tail=x;int last=-1;int temp;int ji;if(x==0){return 0;}if(x==Integer.MAX_VALUE){return 46340;}        while(true){        temp=(tail+head)/2;        if(temp>50000){        tail=50000;        last=50000;        continue;        }        ji=temp*temp;        if(ji==x){        return temp;        }else if(ji>x||ji<0){        if((temp-last)==1||(temp-last)==0){        return last;        }        last=temp;        tail=temp;        continue;        }else{//ji<x                if((last-temp)==1||(last-temp)==0){        return temp;        }                last=temp;        head=temp;        continue;        }        }    }

0 0
原创粉丝点击