price * Ncount번 탔을 때 총 요금에서 money가 얼마나 부족한지 반환0 반환class Solution {
public long solution(int price, int money, int count) {
int totalprice = 0;
for (int i = 1; i <= count; i++) {
totalprice += price * i;
}
return totalprice - money;
}
}
int 오버플로우totalprice를 int로 선언했다.
제한사항에서 price와 count는 최대 2500이다.
루프 안에서 price * i를 count번 누적 합산하면 최댓값은 대략:
2500 * (1 + 2 + ... + 2500) = 2500 * 3,126,250 ≈ 78억
int의 최댓값은 약 21억이므로 오버플로우 발생.
totalprice를 long으로 변경.
long totalprice = 0;
기억할 것: 루프 안에서 반복 곱셈 + 누적이 일어나면
long먼저 의심하자.
totalprice - money가 음수일 때(= 잔돈이 남을 때)도 그냥 반환했다.
삼항연산자로 음수면 0 반환.
return totalprice - money > 0 ? totalprice - money : 0;
주의: 처음에 조건을 반대로 써서
> 0일 때0을 반환하는 실수를 했다.
totalprice - money가 양수 = 모자란 것 = 그 값을 반환해야 한다.
totalprice가 long이어도 루프 안의 price * i는 int * int로 먼저 계산된다.
이번 문제는 2500 * 2500 = 6,250,000으로 int 범위 안이라 괜찮았지만,
곱셈 결과가 클 경우 totalprice가 long이어도 곱셈 단계에서 이미 오버플로우가 발생할 수 있다.
// 안전한 패턴
totalprice += (long) price * i;
class Solution {
public long solution(int price, int money, int count) {
long totalprice = 0;
for (int i = 1; i <= count; i++) {
totalprice += price * i;
}
return totalprice - money > 0 ? totalprice - money : 0;
}
}
| 포인트 | 내용 |
|---|---|
| 오버플로우 체크 | 루프 내 누적 합산은 long 먼저 고려 |
| 반환 조건 | 음수(잔돈 남음) → 0, 양수(부족) → 차액 반환 |
| 삼항 조건 방향 | > 0이면 부족한 것, <= 0이면 여유 있는 것 |
| 곱셈 오버플로우 | long 변수라도 int * int 곱셈은 먼저 캐스팅 필요 |