⏱소요 시간 - 10분
🔑해결 방법
아주 아주 쉬운 문제였다.
if문으로 분기해서 풀어보고, 중복된 코드를 줄이기 위해 max, min을 먼저 정해놓는 두 가지 풀이로 풀어보았다.
Math.max(a,b) : a와 b 중에 큰 수를 리턴
Math.min(a,b) : a와 b 중에 작은 수를 리턴
🔎소스 코드
package step1;
// 두 정수 사이의 합
public class Ex12 {
public static void main(String[] args) {
System.out.println(solution(3, 5));
System.out.println(solution(3, 3));
System.out.println(solution(5, 3));
System.out.println(solution(2, -1));
}
public static long solution(int a, int b) {
long answer = 0;
int max = Math.max(a, b);
int min = Math.min(a, b);
for(int i = min; i <= max; i++) { // i <= max 이므로 a, b가 같을 경우도 포함
answer += i;
}
return answer;
}
}
package step1;
// 두 정수 사이의 합
public class Ex12_1 {
public static void main(String[] args) {
System.out.println(solution(3, 5));
System.out.println(solution(3, 3));
System.out.println(solution(5, 3));
System.out.println(solution(2, -1));
}
public static long solution(int a, int b) {
long answer = 0;
if(a < b) {
for(int i = a; i <= b; i++) {
answer = answer + i;
}
} else if(a > b) {
for(int i = a; i >= b; i--) {
answer = answer + i;
}
} else {
return a;
}
return answer;
}
}
'ALGORITHM' 카테고리의 다른 글
char[] <-> String <-> String[] (0) | 2021.01.12 |
---|---|
[프로그래머스 Java] 문자열 내 마음대로 정렬하기 (0) | 2021.01.12 |
[프로그래머스 Java] 나누어 떨어지는 숫자 배열 (0) | 2021.01.11 |
[프로그래머스 Java] 같은 숫자는 싫어 (0) | 2021.01.10 |
[프로그래머스 Java] 가운데 글자 가져오기 (0) | 2021.01.10 |