Implementint sqrt(int x).

Compute and return the square root of x.

 

逐次逼近

class Solution {
public:
    int sqrt(int x) {
        if(x<2)
            return x;
        int left=1,right=x/2;
        int mid;
        while(left<=right)
        {
            mid=left+(right-left)/2;
            if(x/mid <mid)
                right=mid-1;
            else if(x/mid>mid)
                left=mid+1;
            else
                return mid;
        }
        return right;
    }
};

 

相关文章:

  • 2021-12-30
  • 2022-12-23
  • 2022-12-23
  • 2021-09-08
  • 2021-10-15
  • 2021-10-18
  • 2021-12-01
猜你喜欢
  • 2021-08-25
  • 2022-02-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-14
相关资源
相似解决方案