69. Sqrt(x)

来源:互联网 发布:数据库三大范式详解 编辑:程序博客网 时间:2024/05/16 18:45

Implement int sqrt(int x).

Compute and return the square root of x.

这道题主要用到了二分法;

#include<iostream>#include<cmath>using namespace std;class Solution {public:    int mySqrt(int x)     {        if(x<1)            return 0;        if(x==1)            return 1;        int low=1;        int high=x/2<46340?x/2:46340;//正整数开方最大为46340        while(low<high)        {            int mid=(low+high)/2;            int product=mid*mid;            int greater=(mid+1)*(mid+1);            if(product<=x&&greater>x)                return mid;            else if(product<x)                low=mid+1;            else                high=mid-1;        }        return high;    }};int main(){    int x;    cin>>x;    Solution solve;    cout<<solve.mySqrt(x)<<endl;    return 0;}
0 0