My solution times out for huge inputs, but how can I possibly do this faster???


  • 0
    E

    By faster, I mean without cheating and using a hardcoded list of perfect numbers.

    public class Solution {
        public boolean checkPerfectNumber(int num) {
            if(num <= 0) return false;
            ArrayList<Integer> divisors = getDivisors(num);
            int sum = getSumOfElements(divisors);
            return sum == num;
        }
       //Returns list of divisors 
        private ArrayList<Integer> getDivisors(int num){
            if(num == 0) return null;
            ArrayList<Integer> result = new ArrayList<>();
            for(int i = 1; i <= num / 2; i++){
                if(num % i == 0) result.add(i);
            }
            return result;
        }
       //Returns total of all elements in a list 
        private int getSumOfElements(ArrayList<Integer> list){
            if(list.size() == 0 || list == null) return -1;
            int total = 0;
            for(int i : list) total += i;
            return total;
        }
    }

Log in to reply
 

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