【LeetCode】Perfect Number 解题报告

来源:互联网 发布:将端口号映射到ip地址 编辑:程序博客网 时间:2024/05/21 01:31

【LeetCode】Perfect Number 解题报告

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/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.

Example:Input: 28Output: TrueExplanation: 28 = 1 + 2 + 4 + 7 + 14

Note: The input number n will not exceed 100,000,000. (1e8)

Ways

这个题其实非常简单,循环一遍看看哪些是约数,然后加在一起就行了。注意i从2开始循环,这样不会把1和num自身加进去,最后sum++,把1这个数字加进去。

public class Solution {    public boolean checkPerfectNumber(int num) {        if(num == 1) return false;        int sum = 0;        for(int i = 2; i < Math.sqrt(num);  i++){            if(num % i == 0){                sum += i + num / i;            }        }        sum++;        return sum == num;    }}

Date

2017 年 5 月 16 日

阅读全文
0 0
原创粉丝点击