x的平方根

实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。示例 1:输入: 4
输出: 2
示例 2:输入: 8
输出: 2
说明: 8 的平方根是 2.82842…,
由于返回类型是整数,小数部分将被舍去。

执行用时 :76 ms, 在所有 Python3 提交中击败了27.20% 的用户
内存消耗 :14.1 MB, 在所有 Python3 提交中击败了5.22%的用户

需要调用math。math.floor(x)返回一个小于或者等于x的最大整数

class Solution:
    def mySqrt(self, x: int) -> int:
        import math
        if x>=0:
            x=math.floor(math.sqrt(x))
            return x

在本地运行,在最后直接添加

if __name__=='__main__':
    a=Solution()
    b=a.mySqrt(8)
    c=a.mySqrt(7)
    d=a.mySqrt(0)
    print(b,c,d)

算法题目来自: https://leetcode-cn.com/problems/sqrtx/

posted @ 2019-08-16 14:42  yunduoyun  阅读(119)  评论(0编辑  收藏  举报