두 정수 a, b가 주어졌을 때 a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수, solution을 완성하세요.
예를 들어 a = 3, b = 5인 경우, 3 + 4 + 5 = 12이므로 12를 리턴합니다.
a | b | return |
---|---|---|
3 | 5 | 12 |
3 | 3 | 3 |
5 | 3 | 12 |
class Solution {
public long solution(int a, int b) {
long answer = 0;
int i = 0;
if(a>b){
for(i = 0; i<(a-b); i++){
answer += (b+i);
}
answer+=a;
} else if(b>a){
for(i = 0; i<(b-a); i++){
answer += (a+i);
}
answer+=b;
} else if(b==a) {
return a;
}
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; // 등차수열의 합 공식
}
}
class Solution {
public long solution(int a, int b) {
long answer = 0;
for (int i = ((a < b) ? a : b); i <= ((a < b) ? b : a); i++)
answer += i;
return answer;
}
}
참고사이트: https://school.programmers.co.kr/learn/courses/30/lessons/12912/solution_groups?language=java