leetcode[69]Sqrt(x)

1959 ワード

Implement  int sqrt(int x) .
Compute and return the square root of x.
class Solution {

public:

int sqrt(int x)

{

    long long left=0,right=x/2+1;

    while(left<=right)

    {

        long long mid=(left+right)/2;

        if(mid*mid<=x&&(mid+1)*(mid+1)>x)return (int)mid;

        else if(mid*mid<x) left=mid+1;

        else right=mid-1;

    }

}

/**

int sqrt(int x)

{

    if(x==0)return 0;

    double pre=0,cur=1;

    while(abs(cur-pre)>0.00001)

    {

        pre=cur;

        cur=(pre+x/pre)/2;

    }

    return int(cur);

}

*/

};