binary search

 

class Solution {
public:
    int sqrt(int x) {
        long long base = static_cast<long long>(x);
        long long l = 0;
        long long r = base / 2 + 1;
        while(l <= r) {
            long long mid = l + (r - l)/2;
            if(mid * mid == base) return static_cast<int>( mid);
            if(mid*mid < base) l = mid + 1;
            else r = mid - 1;
        }
        return static_cast<int>(r);
    }
};

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-08
  • 2021-07-31
  • 2021-08-08
猜你喜欢
  • 2021-10-05
  • 2021-08-18
  • 2022-01-25
  • 2021-05-16
  • 2021-07-23
  • 2022-12-23
相关资源
相似解决方案