LeetCode 69. Sqrt(x)

Binary search.

#include <vector>
#include <iostream>
using namespace std;

int sqrt(int x) {
  long long left = 0;
  long long right = x;
  long long xx = x;
  while(left < right) {
    long long mid = (left + right) / 2;
    if(mid * mid <= xx && (mid + 1)* (mid + 1) > xx) {return (int) mid;}
    if(mid * mid < xx) left = mid + 1;
    else if(mid * mid > xx) right = mid - 1;
  }
}

int main(void) {
  int sq = sqrt(4);
  cout << sq << endl;
}


你可能感兴趣的:(LeetCode 69. Sqrt(x))