实现 int sqrt(int x) 函数,计算并返回 x 的平方根。
python:
class Solution: """ @param x: An integer @return: The sqrt of x """ def sqrt(self, x): # write your code here if x == 0: return 0 end = x while int(end) > int(x/end): end = (end + x/end)/2 return int(end)C++:
class Solution { public: /** * @param x: An integer * @return: The sqrt of x */ int sqrt(int x) { // write your code here if(x == 0) { return 0; } long end = x; while(end > x/end) { end = (end + x/end) / 2; } return end; } };PS:注意要使用long,使用int会报错。