Implement int sqrt(int x)
.
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
计算并返回x的平方根,其中x保证为非负整数。
由于返回类型是整数,因此将截断十进制数字,并仅返回结果的整数部分。
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
python实践
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import math
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
# 二分查找法的思想
if x <= 1:
print(x)
return x
# 1. 定义一个数字h,专门用来存放除以2的数
left, right = 0, x
while left <= right:
h = (left + right) // 2
# print(h)
if x // h < h:
right = h - 1
elif x // h > h:
left = h + 1
elif x // h == h:
print(h)
return h
break
print(right)
return right
if __name__ == '__main__':
Solution().mySqrt(x=17)
# print(math.floor(0 + (8 - 0) / 2))
# print(8//1)