Implement int sqrt(int x).
Compute and return the square root of x.
1 class Solution { 2 public: 3 // binary search, overflow values 4 int sqrt(int x) { 5 int i = 0; 6 int j = x / 2 + 1; 7 while (i <= j) 8 { 9 long long mid = i + (j-i) / 2; // not use int 10 long long sq = mid * mid; 11 if (sq == x) return mid; 12 else if (sq < x) i = mid + 1; 13 else j = mid - 1; 14 } 15 return j; 16 } 17 };