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.
Example 1:
Input: 4 Output: 2
my code1:
def compute_sqrt(val):
for i in range(val//2):
if i**2 <= val and (i + 1)**2 > val:
return i
if __name__ == "__main__":
a = int(input("please input the value:"))
print("%d s sqrt value is:"%(a), compute_sqrt(a))
my code2:(时间复杂度Ologn)
def compute_sqrt(val, low, high):
mid = (low + high) // 2
if mid **2 <= val and (mid + 1) **2 > val:
return mid
else:
if (mid + 1) **2 <= val:
return compute_sqrt(val, mid, high) #注意要加上return,只有加上return最终的返回值才能从最内层逐层返回到最外层调用
elif mid **2 > val:
return compute_sqrt(val, low, mid)