题目:
Implement int sqrt(int x)
.
Compute and return the square root of x.
题意:本题是要找一个大于0的整数的开方之后的整数结果,如果有整数结果则返回该结果,若没有整数结果则返回最接近的整数值。因为x>=0,所以求的解肯定在0和x之间,故这里可以使用二分查找来查找结果。因为mid*mid的值可能大于int的最大值,所以使用long来保存mid值。
代码为:
public class Solution { public int mySqrt(int x) { //因为是求一个整数,所以可以使用二分查找 int low =0; int high=x; long mid=(low+high)/2; while(low<=high){ if(mid*mid>x){ high=(int) mid-1; mid=(low+high)/2; }else if(mid*mid<x){ low=(int) mid+1; mid=(low+high)/2; }else{ System.out.println(mid); return (int) mid; }; } System.out.println(high); return high; } }