• 507. Perfect Number 因数求和


    [抄题]:

    We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.

    Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not.

    Example:

    Input: 28
    Output: True
    Explanation: 28 = 1 + 2 + 4 + 7 + 14

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    以为要新开一个动态数组,结果直接加到sum上就能省空间

    以为要全都处理一遍,结果匹配地加上另一半就能省空间

    [一句话思路]:

    一对数匹配的情况,处理一半,另一半用公式就行了

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. sqrt前加Math

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    [复杂度]:Time complexity: O(n) Space complexity: O(1)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

    class Solution {
        public boolean checkPerfectNumber(int num) {
            //cc
            if (num == 1) return false; 
            
            //ini sum = 1;
            int sum = 1;
            
            //for loop
            for (int i = 2; i <= (int)Math.sqrt(num); i++) {
                if (num % i == 0) {
                    sum += i;
                    if (i * i != num) sum += num / i; 
                }
            }
            
            return sum == num;
        }
    }
    View Code
  • 相关阅读:
    hadoop——数据清洗测试
    本地配置hadoop
    从textarea中获取数据后按原样显示
    form自动提交
    艺术和代码的结合 turtle + python 的结合
    python-->微信支付
    python-图片流传输(url转换二维码)
    python-qrcode-二维码
    Java 通过先序中序序列生成二叉树
    Java 实现二叉树的构建以及3种遍历方法
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8986369.html
Copyright © 2020-2023  润新知