leetcode with python:69. Sqrt(x)

题目:

Given a non-negative integer x, compute and return the square root of x.

Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.

Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x * * 0.5

给定一个数x,找出它的平方根,若是小数则无条件捨去

题目明文禁止built-in function
所以直接一行return int(sqrt(x))是不行的,虽然会过
既然sqrt不能用那就用二分搜在1~x的範围中找出x的平方根

class Solution:    def mySqrt(self, x: int) -> int:        l=1        r=x        while l+1!=r:            mid=(l+r)//2            if mid*mid==x:                return mid            if mid*mid>x:                r=mid            if mid*mid<x:                l=mid        return l

一如往常,先设下限l=1跟上限r=x,mid定义为(1+r)//2
mid平方大于x,r降低到mid
mid平方小于x,l提高到mid
一旦mid平方等于x就回传mid
若最后发现l+1=r(表示sqrt(x)是介于l和r之间的小数)
就取l(无条件捨去)
最后执行时间36ms(faster than 94.29%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章