507.Perfect Number
507.Perfect Number
难度:Easy
We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.
1
Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not.
2
Example:
3
Input: 28
4
Output: True
5
Explanation: 28 = 1 + 2 + 4 + 7 + 14
6
Note: The input number n will not exceed 100,000,000. (1e8)
Copied!
求出所有的约数,不过需要注意相加时候的平方根和1.
1
class Solution {
2
public:
3
bool checkPerfectNumber(int num) {
4
if(num<1 ) return false;
5
int s=sqrt(num);
6
bool flag= s*s==num;
7
int sum =1 +flag*s;
8
for(int i=2;i<s+!flag;i++)
9
if(num%i==0) sum+=i+num/i ;
10
11
return sum == num;
12
13
14
}
15
};
Copied!
执行用时 :4 ms, 在所有 C++ 提交中击败了84.67%的用户 内存消耗 :7.9 MB, 在所有 C++ 提交中击败了95.98%的用户
Copy link