Implement int sqrt(int x)
.
Compute and return the square root of x.
class Solution { public: int sqrt(int x) { long long left = 0; long long right = x; while (left <= right) { long long mid = left + (right - left) / 2; if (mid * mid <= x && (mid + 1) * (mid + 1) > x) { return mid; } else if (mid * mid < x) left = mid + 1; else right = mid - 1; } return -1; } };
69. Sqrt(x) (Divide-and-Conquer)
原文:http://www.cnblogs.com/qionglouyuyu/p/4853373.html