LeetCode17—— x 的平方根
前言:
题目内容:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sqrtx
python实现:
方法一
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
return int(x**0.5)
if __name__ == '__main__':
x=10
aa = Solution()
print(aa.mySqrt(x))
方法二
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x <= 1:
return x
r = x
while r > x / r:
r = (r + x / r) // 2
return r
if __name__ == '__main__':
x=10
aa = Solution()
print(aa.mySqrt(x))
方法三
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x == 1:
return 1
low = 0
up = x
while low + 1 < up:
mid = (low + up) // 2
if mid * mid < x:
low = mid
elif mid * mid > x:
up = mid
else:
return mid
return low
if __name__ == '__main__':
x=10
aa = Solution()
print(aa.mySqrt(x))