C++ with explaination


  • 0
    class Solution {
    public:
        bool checkPerfectNumber(int num) {
            //exclude the special condition
            //though the question said num is positive, the test cases include num=0
            if(num <= 0) return false;
            
            //for example, num=100;
            //sum = (1,100) + (2,50) + (4,25) + (5,20) 
            int sum = 0;
            int i;
            for(i = 1; i*i < num; ++i) {
                if(num%i == 0) sum += i + num/i;
            }
            
            //adjust sum to get rid of the extra addition
            //for example when num=100, need to add 10 to sum
            //sum = (1,100) + (2,50) + (4,25) + (5,20) + 10 - 100
            if(i*i == num)
                sum = sum + i - num;
            else
                sum -= num;
        
            return num == sum;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.