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
Note: The input number n will not exceed 100,000,000. (1e8)
链接:https://leetcode.com/problems/perfect-number/#/description
3/31/2017
注意1要返回false
1 public class Solution { 2 public boolean checkPerfectNumber(int num) { 3 if (num <= 1) return false; 4 Set<Integer> s = new HashSet<Integer>(); 5 s.add(1); 6 7 for (int i = 2; i <= Math.sqrt(num); i++) { 8 if (num % i == 0) { 9 s.add(i); 10 s.add(num / i); 11 } 12 if (i == num / i) break; 13 } 14 if (s.size() == 0) return false; 15 int sum = 0; 16 for (Integer v : s) sum += v; 17 return sum == num; 18 } 19 }
别人的算法,更加节省空间复杂度,第11行是加上1
https://discuss.leetcode.com/topic/84259/simple-java-solution
1 public class Solution { 2 public boolean checkPerfectNumber(int num) { 3 if (num == 1) return false; 4 5 int sum = 0; 6 for (int i = 2; i <= Math.sqrt(num); i++) { 7 if (num % i == 0) { 8 sum += i + num / i; 9 } 10 } 11 sum++; 12 13 return sum == num; 14 } 15 }
有人提醒test case缺失,不要加相同元素两遍。
https://discuss.leetcode.com/topic/84337/missing-test-cases
更多讨论: