웹 프로그래밍

[프로그래머스(Programmers)] 두 정수 사이의 합 - JAVA 본문

프로그래머스/level1

[프로그래머스(Programmers)] 두 정수 사이의 합 - JAVA

B. C Choi 2021. 10. 26. 21:46

 

문제 설명

 

두 정수 a, b가 주어졌을 때 a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수, solution을 완성하세요.

예를 들어 a = 3, b = 5인 경우, 3 + 4 + 5 = 12이므로 12를 리턴합니다.

 


 

제한 조건

 

1. a와 b가 같은 경우는 둘 중 아무 수나 리턴하세요.

2. a와 b는 -10,000,000 이상 10,000,000 이하인 정수입니다.

3, a와 b의 대소관계는 정해져 있지 않습니다.

 


 

입출력 예

a b return
3 5 12
3 3 3
5 3 12

 


 

풀이

1) Math함수를 이용한 방법

class Solution {
    public long solution(int a, int b) {
        long answer = 0;
        
        for(int i = Math.min(a,b); i <= Math.max(a,b); i++) {
            if(a == b) {
                answer = a;
            } else {
                answer += i;
            }
        } 
        return answer;
    }
}


2)  제어문, 반복문만 사용한 방법

class Solution {
    public long solution(int a, int b) {
        long answer = 0;
        
        if(a > b) {
            for(int i = b; i <= a; i++) {
                answer += i;
            } 
        } else {
            for(int i = a; i <= b; i++) {
                answer += i;
            }
        }
        return answer;
    }
}


3) 등차수열 알고리즘(Math함수)으로 해결하는 방법 

class Solution {
    public long solution(int a, int b) {
        long answer = 0;
        
        long min = Math.min(a, b);
        long max = Math.max(a, b);
        
        answer = (max - min + 1) * (min + max) / 2;
        return answer;
    }
}


성능:  3 > 1 > 2

속도 : 3 > 2 > 1