728x90
https://school.programmers.co.kr/learn/courses/30/lessons/12928
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
내 코드, 정답!
class Solution {
public int solution(int n) {
int answer = 0;
for(int i=1; i<= n; i++){
if(n % i == 0){
answer += i;
}
}
return answer;
}
}
처음에는 무심코 int i=0; 으로 했다가 Java lang ArithmeticException by zero 오류가 났었다, i=1로 바꿔서 해결!
다른 사람의 코드!
num/2 를 해서 for문을 절반만 돌아가게 한다음
answer에 num를 더 해주는 방식으로
num이 12이 경우, 12의 약수는 1, 2, 3, 4, 6, 12입니다. 이를 모두 더하면 28이다.
num/2는 6이고, 6의 약수까지를 더한다음, answer에 num에서 12만 더해준다
오호! 효율적이네
https://github.com/saehee15/Programmers/blob/main/Level1/SumDivisor.java
GitHub - saehee15/Programmers: 프로그래머스(programmers) 문제풀이
프로그래머스(programmers) 문제풀이. Contribute to saehee15/Programmers development by creating an account on GitHub.
github.com
728x90
'TIL > programmers' 카테고리의 다른 글
[프로그래머스/JAVA] 제일 작은 수 제거하기 (0) | 2022.08.03 |
---|