LeetCode-Perfect Number

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/88796503

Description:
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)

题意:计算整数N是否为Perfect Number,其定义为满足其所有因数(不包括自身)的和与该数相等;

解法:只需要计算其所有因数并求和后与此数相比较即可,这里需要注意的是给出的整数N可能为负数或零,而Perfect Number要求是正整数;

Java
class Solution {
    public boolean checkPerfectNumber(int num) {
        int sum = 0;
        for (int i = 1; i <= num / 2; i++) {
            if (num % i == 0) sum += i;
        }
        return num <= 0 || num != sum ? false : true;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/88796503