507. Perfect Number LeetCode Solution

In this guide, you will get 507. Perfect Number LeetCode Solution with the best time and space complexity. The solution to Perfect Number problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Perfect Number solution in C++
  4. Perfect Number solution in Java
  5. Perfect Number solution in Python
  6. Additional Resources
507. Perfect Number LeetCode Solution image

Problem Statement of Perfect Number

A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly.
Given an integer n, return true if n is a perfect number, otherwise return false.

Example 1:

Input: num = 28
Output: true
Explanation: 28 = 1 + 2 + 4 + 7 + 14
1, 2, 4, 7, and 14 are all divisors of 28.

Example 2:

Input: num = 7
Output: false

Constraints:

1 <= num <= 108

Complexity Analysis

  • Time Complexity: O(\sqrt{n}) \to O(1)
  • Space Complexity: O(1)

507. Perfect Number LeetCode Solution in C++

class Solution {
 public:
  bool checkPerfectNumber(int num) {
    if (num == 1)
      return false;

    int sum = 1;

    for (int i = 2; i <= sqrt(num); ++i)
      if (num % i == 0)
        sum += i + num / i;

    return sum == num;
  }
};
/* code provided by PROGIEZ */

507. Perfect Number LeetCode Solution in Java

class Solution {
  public boolean checkPerfectNumber(int num) {
    if (num == 1)
      return false;

    int sum = 1;

    for (int i = 2; i <= Math.sqrt(num); ++i)
      if (num % i == 0)
        sum += i + num / i;

    return sum == num;
  }
}
// code provided by PROGIEZ

507. Perfect Number LeetCode Solution in Python

class Solution:
  def checkPerfectNumber(self, num: int) -> bool:
    return num in {6, 28, 496, 8128, 33550336}
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.