본문 바로가기

프로그래머스/lv1

두 정수 사이의 합

/* 두 정수 사이의 합
 * 두 정수 a, b가 주어졌을 때
 * a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수, solution을 완성하세요.
 *
 * a와 b가 같은 경우는 둘 중 아무 수나 리턴하세요.
 * a와 b는 -10,000,000 이상 10,000,000 이하인 정수입니다.
 * a와 b의 대소관계는 정해져있지 않습니다.
 *
 * a    b   return
 * 3    5   12
 * 3    3   3
 * 5    3   12
 */
 
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
public class programmer_1_19 {
    static int a1 = 3;  static int b1 = 5;
    static int a2 = 3;  static int b2 = 3;
    static int a3 = 5;  static int b3 = 3;
    public long solution(int a, int b) {
        long answer = 0;
        long min = a >= b ? b : a;
        long max = a >= b ? a : b;
        
        for(long i = min; i <= max; i++){
            answer += i;
        }
        return answer;
    }
    public static void main(String args[]){
        programmer_1_19 t = new programmer_1_19();
        System.out.println("---------------------------------------");
        System.out.println("result = " + t.solution(a1,b1));
        System.out.println("---------------------------------------");
        System.out.println("result2 = " + t.solution(a2,b2));
        System.out.println("---------------------------------------");
        System.out.println("result3 = " + t.solution(a3,b3));
        System.out.println("---------------------------------------");
    }
}
 
cs

'프로그래머스 > lv1' 카테고리의 다른 글

서울에서 김서방 찾기  (0) 2022.12.14
콜라츠 추측  (0) 2022.12.13
나머지가 1이 되는 수 찾기  (1) 2022.12.13
정수 내림차순으로 배치하기  (0) 2022.12.13
하샤드 수  (0) 2022.12.13