前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T203-完美数

【leetcode刷题】T203-完美数

作者头像
木又AI帮
发布2019-11-28 22:16:14
2980
发布2019-11-28 22:16:14
举报
文章被收录于专栏:木又AI帮木又AI帮

木又连续日更第70天(70/100)


木又的第203篇leetcode解题报告

数学类型第19篇解题报告

leetcode第507题:完美数

https://leetcode-cn.com/problems/perfect-number/


【题目】

对于一个 正整数,如果它和除了它自身以外的所有正因子之和相等,我们称它为“完美数”。

给定一个 整数 n, 如果他是完美数,返回 True,否则返回 False

代码语言:javascript
复制
示例:

输入: 28
输出: True
解释: 28 = 1 + 2 + 4 + 7 + 14

【思路】

直接遍历,得到所有正因子。有两个问题:

一是不用遍历到num,只用遍历到sqrt(num)即可,否则会超时;

二是<=2的数都不是,可以直接返回False

【代码】

python版本

代码语言:javascript
复制
class Solution(object):
    def checkPerfectNumber(self, num):
        """
        :type num: int
        :rtype: bool
        """
        # 特殊情况
        if num <= 1:
            return False

        res = -num
        for i in range(1, int(math.sqrt(num)) + 1):
            if num % i == 0:
                res += i + num / i
        return res == num

C++版本

代码语言:javascript
复制
class Solution {
public:
    bool checkPerfectNumber(int num) {
        if(num < 2)
            return false;
        int res = -num;
        for(int i=1; i<(int)sqrt(num)+1; i++){
            if(num % i == 0)
                res += i + num / i;
        }
        cout << res << endl;
        return res == num;
    }
};
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-11-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档