알고리즘 풀이/프로그래머스

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

데롱디롱 2021. 8. 30. 14:18
728x90

- a와 b 중 작은 것을 구별해서 for문 조건에 넣고 answer에 계속 더하면 된다.

등차수열의 합 공식으로 간단하게 구할 수도 있다.
Sn = n(2a1 + (n-1)d) / 2

 

 

class Solution {
    public long solution(int a, int b) {
        long answer = 0;
        int start = Math.min(a, b);
        int end = Math.max(a, b);

        for (int i = start; i <= end; i++)
            answer += i;

        return answer;
    }
}
댓글수0