티스토리 뷰

PS/programmers

Level1) 두 정수 사이의 합

kingsubin 2020. 9. 8. 15:44
class Solution {
    public long solution(int a, int b) {
        long big = Math.max(a, b);
        long small = Math.min(a, b);
        long answer = 0;

        for (long i = small; i <= big; i++) {
            answer += i;
        }
        return answer;
    }
}

- 작은거 부터 큰거까지 더하기 

 

 

class Solution {

    public long solution(int a, int b) {
        return sumAtoB(Math.min(a, b), Math.max(b, a));
    }

    private long sumAtoB(long a, long b) {
        return (b - a + 1) * (a + b) / 2;
    }
}

- 다른 사람 등차수열로 풀이

- 뭔가 생각 해 볼만했는데 공식 생각이 안났다 ...