Study/Programmers

[프로그래머스 Lv.1] 두 정수 사이의 합

0lynny 2021. 7. 6. 20:51

두 정수 사이의 합

 

문제 설명

두 정수 a, b가 주어졌을 때 a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수, solution을 완성하세요.
예를 들어 a = 3, b = 5인 경우, 3 + 4 + 5 = 12이므로 12를 리턴합니다.

 

제한 조건

  • a와 b가 같은 경우는 둘 중 아무 수나 리턴하세요.
  • a와 b는 -10,000,000 이상 10,000,000 이하인 정수입니다.
  • a와 b의 대소관계는 정해져있지 않습니다.

코드 구현

a와 b사이의 대소관계이 되어있지 않기 때문에, a, b의 값을 비교하여 a가 더 큰 수일 경우, a와 b를 바꾸었음.

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

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

 

다른 사람의 풀이 (출처: 패터쓴님의 코드)

: 반복문 없이도 해결할 수 있다는 것을 알게 되었다.

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

long long solution(int a, int b) {
    if(a==b) return a;

    //sum of the smallest and the biggest
    //multiply it by the number of numbers
    //between a and be divided by 2.
    int sum = a+b, num = b-a+1; 

    if (a>b) //if a is greater, replace num.
        num = a-b+1;

    return (long long) sum*num/2; //cast the number type 
}