본문 바로가기

컴퓨터공학

[프로그래머스/ C++]두 정수 사이의 합

반응형
#include <string>
#include <vector>

using namespace std;

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

 

아래 코드는 합 공식을 이용하여 짧게 작성된 코드이다.

#include <string>
#include <vector>

using namespace std;

long long solution(int a, int b) {
    return (long long)(a + b) * (abs(a - b) + 1) / 2;
}
반응형