7.Perfect Number

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.

 

解题思路:

  直接求出所有约数然后相加,结果与目标数字相等即可。

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

 

posted @ 2017-04-09 22:20  legooooo  阅读(138)  评论(0编辑  收藏  举报