Implement int sqrt(int x)
.
Compute and return the square root of x.
1、二分法
class Solution { public: int sqrt(int x) { if(x < 0) return -1; long long target = (long long)x; long long left = 0; long long right = target; long long mid; while(left <= right){ mid = left + (right - left) / 2; if(mid * mid == target || (mid * mid < target && (mid + 1) * (mid + 1) > target)){ return (int)mid; } else if(mid * mid < target){ left = mid + 1; } else{ right = mid - 1; } } } };
class Solution { public: int sqrt(int x) { if(x < 0) return -1; double n=x; while(abs(n*n-x)>0.0001)n=(n+x/n)/2; return (int)n; } };
原文:http://blog.csdn.net/starcuan/article/details/18843641