| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 30 |
Tags
- java
- 방사성 동위원소 치료
- kotlin
- Android Compose
- 카페
- 자바
- 갑상선암
- 정렬 알고리즘
- firebase
- leetcode
- Android
- 폐CT
- 알고리즘
- 입원
- 백준알고리즘
- 동위원소치료
- 맛집
- 전이
- 임파선전이
- 객체
- android auto
- 방사성동위원소치료
- 림프절전이
- 안드로이드
- 수술
- 코틀린
- 프로그래머스
- 저요오드식
- Compose
- MYSQL
Archives
- Today
- Total
새우버거의 개발 블로그
[JAVA] 프로그래머스 Lv.2 : 숫자의 표현 본문

예제:
| n | result |
| 15 | 4 |
Solution #1
class Solution {
public int solution(int n) {
int answer = 0;
int index = 1, sum = 0;
while (index <= n) {
for (int i = index; i <= n; i++) {
sum += i;
if (sum == n) answer++;
}
sum = 0;
index++;
}
return answer;
}
}
Result #1

💡 while 반복문과 for 반복문을 사용해서 풀었다. 효율성 테스트에서 시간 초과가 나왔다.
혹시 예외 조건에 break; 를 추가해야 했나?
Solution #2
class Solution {
public int solution(int n) {
int answer = 0;
int index = 1, sum = 0;
while (index <= n) {
for (int i = index; i <= n; i++) {
sum += i;
if (sum == n) answer++;
else if (sum > n) break;
}
sum = 0;
index++;
}
return answer;
}
}
Result #2

💡 break; 추가하니 통과
반복문을 사용할 때는 예외 처리를 하느냐에 따라 효율성이 많이 달라진다는 것을 알게 되었다.
More Algorithm!
👇👇
github.com/ggujangi/ggu.programmers
ggujangi/ggu.programmers
프로그래머스 알고리즘, JAVA. Contribute to ggujangi/ggu.programmers development by creating an account on GitHub.
github.com
출처 : 프로그래머스
'프로그래머스 - JAVA > Level 2' 카테고리의 다른 글
| [JAVA] 프로그래머스 Lv.2 : 올바른 괄호 (0) | 2021.06.23 |
|---|---|
| [JAVA] 프로그래머스 Lv.2 : 땅따먹기 (0) | 2021.06.23 |
| [JAVA] 프로그래머스 Lv.2 : 최댓값과 최솟값 (0) | 2021.06.09 |
| [JAVA] 프로그래머스 Lv.2 : 피보나치 수 (0) | 2021.06.09 |
| [JAVA] 프로그래머스 Lv.2 : 최솟값 만들기 (0) | 2021.06.08 |