LeetCode 69. Sqrt(x) x 的平方根

链接

https://leetcode-cn.com/problems/sqrtx/description/

要求

实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。

输入: 4
输出: 2

输入: 8
输出: 2

相关代码

import random


class Solution(object):
    def mySqrt(self, x):

        if x == 1:
            return x

        start = 0
        end = x

        while end - start > 1:
            random_count = random.randint(start, end)
            if random_count * random_count == x:
                return random_count
            elif random_count * random_count > x:
                end = random_count
            else:
                start = random_count

        return start

心得体会

random用法

import random

student = ['lee', 'kim', 'zhang']

print random.choice(student)  #列表或字符串中随机选取一个
print random.choice('tomorrow') 
print random.sample(student, 2) #列表或字符串中随机选取指定个数,返回类型为列表
print random.sample('tomorrow',2)
print random.random() # 随机产生0到1之间的浮点数
print random.randint(1,10) # 输出指定范围内的整数型随机数

# 打乱列表顺序 注意不是直接print
random.shuffle(student)
print student

print结果

# 第一次
zhang
t
['lee', 'zhang']
['m', 'o']
0.490747748629
2
['zhang', 'kim', 'lee']

# 第二次
lee
r
['zhang', 'lee']
['r', 'r']
0.979752945641
8
['lee', 'zhang', 'kim']

你可能感兴趣的:(LeetCode 69. Sqrt(x) x 的平方根)