69. Sqrt(x)

来源:互联网 发布:幼儿认字软件 编辑:程序博客网 时间:2024/05/19 08:01

Implement int sqrt(int x).

Compute and return the square root of x.

题意:求x的平方根。

直接看代码:

public class Solution {    public int mySqrt(int x) {        if(x == 0)            return 0;        if(x ==1 || x==2 || x==3)            return 1;        int left = 2;        int right = x/2;        while(true){            int mid = left + (right-left)/2;            if(mid > x/mid){                right = mid-1;            }else{                if(mid+1 > x/(mid+1))                    return mid;                left = mid+1;            }        }    }}
通过二分法,在2和x/2中寻找答案。

原创粉丝点击