[LeetCode/Kotlin]Easy - 507. Perfect Number
2025. 2. 28. 10:42ㆍLeetCode/Kotlin | Easy
728x90
반응형
https://leetcode.com/problems/perfect-number/description/
문제
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
풀이
풀이 접근 과정
입력 받은 num의 소인수들을 배열에 저장해서 그것들의 합을 구함 → 메모리 Up!!
배열을 빼고 그때 그때 소인수들의 합을 계산.
중복된 값은 계산할 필요가 없기 때문에 num의 제곱근까지만 계산
최종 소스코드
class Solution {
fun checkPerfectNumber(num: Int): Boolean {
if (num <= 1) return false
var divisors = 1
for (i in 2 .. sqrt(num.toDouble()).toInt()) {
if (num % i == 0) {
divisors += i
divisors += (num/i)
}
}
return divisors == num
}
}
- 입력 받은 num이 1보다 같거나 작으면 false 리턴
- 소인수들의 합을 계산할 divisors의 초기값은 1
- 2부터 num의 제곱근까지 돌아가는 반복문에서 num이 나누어 떨어지면 divisors에 합함
- divisors의 값이 num과 일치하면 true, 일치하지 않으면 false
Comment
So EEEEEEEEEEEasy

728x90
반응형
'LeetCode > Kotlin | Easy' 카테고리의 다른 글
[LeetCode/Kotlin]344. Reverse String (0) | 2024.07.08 |
---|---|
[LeetCode/Kotlin]Easy - 13. Roman to Integer (0) | 2024.05.09 |
[LeetCode/Kotlin]Easy - 278. First Bad Version (0) | 2024.04.12 |
[LeetCode/Kotlin]Easy - 1. Two Sum (0) | 2023.10.13 |
[LeetCode/Kotlin]Easy - 506. Relative Ranks (0) | 2023.09.19 |