您的位置:首页 > 编程语言 > Java开发

leetCode练习(69)

2016-10-13 20:27 260 查看
题目: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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode int