实现sqrt()函数
方法一:
int mySqrt(int x) { if(x == 0) { return 0; } int ans = exp(0.5*log(x)); int k = ans+1; //int r = k*k; if((long long) k*k <=x) { return k; } else { return ans; } }
方法二:二分查找
int mySqrt(int x) { int l = 0, r = x, ans = -1; while (l <= r) { int mid = l + (r - l) / 2; if ((long long)mid * mid <= x) { ans = mid; l = mid + 1; } else { r = mid - 1; } } return ans; }