[LeetCode] Perfect Number 完美数字
2017-03-28 21:07
337 查看
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:
Note: The input number n will not exceed 100,000,000. (1e8)
这道题让我们判断给定数字是否为完美数字,并给来完美数字的定义,就是一个整数等于除其自身之外的所有的因子之和。那么由于不能包含自身,所以n必定大于1。其实这道题跟之前的判断质数的题蛮类似的,都是要找因子。由于1肯定是因子,可以提前加上,那么我们找其他因子的范围是[2, sqrt(n)]。我们遍历这之间所有的数字,如果可以被n整除,那么我们把i和num/i都加上,对于n如果是平方数的话,那么我们此时相同的因子加来两次,所以我们要减掉一次。还有就是在遍历的过程中如果累积和sum大于n了,直接返回false即可。在循环结束后,我们看sum是否和num相等,参见代码如下:
解法一:
下面这种方法叼的不行,在给定的n的范围内其实只有五个符合要求的完美数字,于是就有这种枚举的解法,那么套用一句诸葛孔明的名言就是,我从未见过如此厚颜无耻之解法。哈哈,开个玩笑。写这篇博客的时候,国足正和伊朗进行十二强赛,上半场0比0,希望国足下半场能进球,好运好运,不忘初心,方得始终~
解法二:
参考资料:
https://discuss.leetcode.com/topic/84259/simple-java-solution
LeetCode All in One 题目讲解汇总(持续更新中...)
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
Note: The input number n will not exceed 100,000,000. (1e8)
这道题让我们判断给定数字是否为完美数字,并给来完美数字的定义,就是一个整数等于除其自身之外的所有的因子之和。那么由于不能包含自身,所以n必定大于1。其实这道题跟之前的判断质数的题蛮类似的,都是要找因子。由于1肯定是因子,可以提前加上,那么我们找其他因子的范围是[2, sqrt(n)]。我们遍历这之间所有的数字,如果可以被n整除,那么我们把i和num/i都加上,对于n如果是平方数的话,那么我们此时相同的因子加来两次,所以我们要减掉一次。还有就是在遍历的过程中如果累积和sum大于n了,直接返回false即可。在循环结束后,我们看sum是否和num相等,参见代码如下:
解法一:
class Solution { public: bool checkPerfectNumber(int num) { if (num == 1) return false; int sum = 1; for (int i = 2; i * i <= num; ++i) { if (num % i == 0) sum += (i + num / i); if (i * i == num) sum -= i; if (sum > num) return false; } return sum == num; } };
下面这种方法叼的不行,在给定的n的范围内其实只有五个符合要求的完美数字,于是就有这种枚举的解法,那么套用一句诸葛孔明的名言就是,我从未见过如此厚颜无耻之解法。哈哈,开个玩笑。写这篇博客的时候,国足正和伊朗进行十二强赛,上半场0比0,希望国足下半场能进球,好运好运,不忘初心,方得始终~
解法二:
class Solution { public: bool checkPerfectNumber(int num) { return num==6 || num==28 || num==496 || num==8128 || num==33550336; } };
参考资料:
https://discuss.leetcode.com/topic/84259/simple-java-solution
LeetCode All in One 题目讲解汇总(持续更新中...)
相关文章推荐
- LeetCode 507 Perfect Number(完美数字)
- leetcode 507. Perfect Number 完美数字
- LeetCode学习(2) 将罗马数字转换为数字
- LeetCode 216. Combination Sum III(数字之和)
- Leetcode:728. Self Dividing Numbers(是否为分裂数字)
- Leetcode刷题记——13. Roman to Integer(罗马数字转换阿拉伯数字)
- [leetcode:13] 罗马数字转十进制
- python解leetcode——13.Roman to Integer (罗马数字转为整数)
- leetCode 9.Palindrome Number (回文数字) 解题思路和方法
- Leetcode:Triangle 数字三角形
- [LeetCode386]Lexicographical Numbers(n以内的数字按字典序输出)
- LeetCode:只出现一次的数字
- [LeetCode] 373. Find K Pairs with Smallest Sums 找和最小的K对数字
- LeetCode 246. Strobogrammatic Number (可颠倒数字) $
- LeetCode-Add Two Numbers-链表数字相加-链表操作+加法进位
- [LeetCode] 65. Valid Number 验证数字
- leetcode_374. Guess Number Higher or Lower 猜数字是比给定的数字高了还是低了,二分查找法
- 每日一题 LeetCode 有效的数字 Python实现
- [LeetCode] Add Digits 加数字
- 【BZOJ1853/2393】[Scoi2010]幸运数字/Cirno的完美算数教室 DFS+容斥