알고리즘

[프로그래머스] 두 정수 사이의 합

건뱅 2019. 4. 17.
반응형

일주일에 알고리즘 두문제풀기 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
 
import java.util.Scanner;
 
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
 

 

<결과화면>

 

조건문을 적을때 파라미터 값을 이용해서 조건식을 만들었더니 값이 계속 다르게 나왔다.

정확한 값을 위해서는 조건식을 변수를 따로 선언하여 만드는 쪽으로 생각을 하는게 좋을 것 같다.

반응형

댓글