[抄题]:
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上就能省空间
以为要全都处理一遍,结果匹配地加上另一半就能省空间
[一句话思路]:
一对数匹配的情况,处理一半,另一半用公式就行了
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- 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; } }