프로그래머스

두 정수 사이의 합

backend_fighting 2022. 12. 19. 23:46
728x90

나의코드

class Solution {
    public long solution(int a, int b) {
        long answer = 0;
        long maxVal = b;
        int temp =0;
        if(maxVal<a)
        {
            temp =a;
            a = b;
            b = temp;
        }
        for(int i=a;i<=b;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;
    }
}

등차 수열의 공식으로 풀었다. 수학문제였구나 깨달았다.

728x90