码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode507. 完美数

时间:2019-05-25 12:51:56      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:bool   style   超出   bsp   turn   port   sel   mat   imp   

超出时间限制改进

28 = 1 + 2 + 4 + 7 + 14

循环从1到sqrt(28)

每次加上 i 和 num/i

比如 2 和 14 

class Solution:
    def checkPerfectNumber(self, num: int) -> bool:
        import math
        if num <= 1:
            return False
        ans = 0
        for i in range(1, int(math.sqrt(num)) + 1, 1):
            if num % i == 0:
                ans += i
                if i != 1 and num / i != i:
                    ans += num / i
        return ans == num

 

leetcode507. 完美数

标签:bool   style   超出   bsp   turn   port   sel   mat   imp   

原文地址:https://www.cnblogs.com/woshizhizhang/p/10921866.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!