Leetcode.求x的平方根
题目
求x的平方根,保留整数部分;
题目难度:简单
方法一:调用函数sqrt()
第一开始就想到使用sqrt()函数,瞬间通过。但是看了评论区,我这样的应该直接被面试官赶出去吧。。。。。
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
#返回某个数的平方根
ans = int(math.sqrt(x))
return ans
方法二:使用袖珍计算器法
这个方法表示使用指数函数和对数函数来表示平方根,是偏向数学的方法。
所以利用exp()函数和log()函数就可以求x的平方根了
if x == 0:
return 0
ans = int(math.exp(0.5 * math.log(x)))
return ans+1 if (ans+1)**2 <= x else ans
方法三:使用二分法
ans = -1
low,high = 0,x
while