if - else if - else
for
문을 사용해보자for(int i = a; i <= b; i++)
for(int i = b; i <= a; i++)
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 if (a > b) {
for (int i = b; i <= a; i++) {
answer+=i;
}
} else {
answer = 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;
}
}
Math.min(), Math.max() 로 대소비교를 해 sumAtoB 함수 인자에 넣어주고 sumAtoB에서 등차수열 공식 을 활용한 풀이
Math.max() 함수는 인자 중 큰 값을 리턴, Math.min() 함수는 인자 중 작은 값을 리턴한다.
사용법
System.out.println(Math.max(17, 1);
System.out.println(Math.min(2.4, 4.9);
17
2.4