[프로그래머스] [LV1] 두 정수 사이의 합
업데이트:
📚 두 정수 사이의 합
난이도 ⭐️
📖 문제
📝 내 풀이
class Solution {
public long solution(int a, int b) {
long answer = 0;
if(a < b){
for(int i = a; i <= b; i++)
answer += i;
}
else{
for(int i = b; i <= a; 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;
}
}
댓글남기기