LeetCode Easy: 69. Sqrt(x)

一、题目

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

返回一个非负整数的平方根

二、题目解析

这个可以用二分查找来做,如果用暴力搜索的话会超时,哈哈,调侃一下,小白慢慢入门了,遇到搜索问题,首先就想到二分查找而不是暴力搜索,注意最后如果是小数的话,是返回不大于此数的部分。

三、代码

#coding:utf-8
def mySqrt(x):
    """
    :type x: int
    :rtype: int
    """
    while x<2:
        return x
    first = 1
    last = x//2
    while first <= last:
        mid = (first + last) // 2
        if mid*mid == x:
            print(mid)
            return mid
        if mid*mid < x:
            first = mid+1
            number = mid
        else:
            last = mid -1
    print(number)
    return number

  

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8674246.html