반응형
일주일에 알고리즘 두문제풀기 2주차!
간단한 문제를 풀면서도 사소하게라도 내 코딩습관의 문제를 알아가는 재미가 있다.
이번에 풀어본 문제는 두 정수 사이의 합을 구하는 문제다.
<문제↓>
<작성코드>
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
31
32
33
34
35
36
37
38
39
40
41
42
43
|
package com.java.programers;
public class Solution2 {
public static long solution(int a, int b) {
long answer = 0;
int max, min;
if (a == b) { // a와 b가 같은 수
answer = a;
} else if (a > b) { // a가 b보다 클 때
max = a;
min = b;
for (int i = 0; i <= max - min; i++, b++) {
answer += b;
}
} else if (a < b) { // b가 a보다 클 때
max = b;
min = a;
for (int i = 0; i <= max - min; i++, a++) {
answer += a;
}
}
return answer;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("두 정수 a,b를 입력하세요");
int a = scanner.nextInt();
if (a == 0) {
break;
}
int b = scanner.nextInt();
System.out.println("a: " + a + " b: " + b + " \n두 정수사이의 합: " + solution(a, b));
}
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4f; text-decoration:none">Colored by Color Scripter
|
<결과화면>
조건문을 적을때 파라미터 값을 이용해서 조건식을 만들었더니 값이 계속 다르게 나왔다.
정확한 값을 위해서는 조건식을 변수를 따로 선언하여 만드는 쪽으로 생각을 하는게 좋을 것 같다.
반응형
'알고리즘' 카테고리의 다른 글
[프로그래머스] 콜라츠 추측 (0) | 2019.04.26 |
---|---|
[프로그래머스] 시저암호 (2) | 2019.04.23 |
[프로그래머스] 나누어 떨어지는 숫자 배열 (4) | 2019.04.18 |
[프로그래머스] 가운데 글자 가져오기 (1) | 2019.04.12 |
[프로그래머스] 완주하지 못한 선수 (1) | 2019.04.11 |
댓글