Lintcode:x的平方根

    xiaoxiao2023-11-11  164

    问题:

    实现 int sqrt(int x) 函数,计算并返回 x 的平方根。

    样例:

    样例 1: 输入: 0 输出: 0 样例 2: 输入: 3 输出: 1 样例解释: 返回对x开根号后向下取整的结果。 样例 3: 输入: 4 输出: 2

    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会报错。

    最新回复(0)