LeetCode Weekly Contest 25 之 507.Perfect Number

来源:互联网 发布:java @apect 编辑:程序博客网 时间:2024/06/02 07:16

LeetCode Weekly Contest 25

赛题

本次周赛主要分为以下4道题:

  • 507 Perfect Number (3分)
  • 537 Complex Number Multiplication (6分)
  • 545 boundary of Binary Tree (8分)
  • 546 Remove Boxes (9分)

507 Perfect Number

Problem:

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: 28
Output: True
Explanation: 28 = 1 + 2 + 4 + 7 + 14

Note

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

没有什么难度的题,思路在题目中已经给你了,无非是在遍历条件上做点思考。

My first solution(14ms)

public boolean checkPerfectNumber(int num) {        //边界条件        if(num == 0 || num == 1) return false;        //第二部分        int sum = 1;        for (int i = 2; i * i <= num; i++) {            if (num % i == 0){                sum += i + num / i;            }        }        return sum == num;    }

注意一些细节,Perfect Number不能由它自己组成,所以排除0和1。num由两个相乘的数分解,所以遍历时只需要遍历num个数即可,所以遍历条件为i*i <= num,注意等于号。

0 0
原创粉丝点击