https://school.programmers.co.kr/learn/courses/30/lessons/120923
연속된 세 개의 정수를 더해 12가 되는 경우는 3, 4, 5입니다. 두 정수 num
과 total
이 주어집니다. 연속된 수 num
개를 더한 값이 total
이 될 때, 정수 배열을 오름차순으로 담아 return하도록 solution함수를 완성해보세요.
1 ≤ num ≤ 100
0 ≤ total ≤ 1000
num개의 연속된 수를 더하여 total이 될 수 없는 테스트 케이스는 없습니다.
num | total | result |
---|---|---|
3 | 12 | [3, 4, 5] |
5 | 15 | [1, 2, 3, 4, 5] |
4 | 14 | [2, 3, 4, 5] |
5 | 5 | [-1, 0, 1, 2, 3] |
num = 3, total = 12인 경우 [3, 4, 5]를 return합니다.
num = 5, total = 15인 경우 [1, 2, 3, 4, 5]를 return합니다.
4개의 연속된 수를 더해 14가 되는 경우는 2, 3, 4, 5입니다.
설명 생략
import java.util.Arrays;
class Solution {
public int[] solution(int num, int total) {
int[] answer = new int[num];
boolean isLoop=true;
if(total==0){ //num/2 *(-1)부터
int start=num/2*(-1);
for(int i=0;i<num;i++){
answer[i]=start;
start++;
}
}
else if(num==total){
int start=num;
int nowstart=0;
while(isLoop){
int sum=0;
nowstart=start;
for(int i=0;i<num;i++){
sum+=start;
start--;
}
if(sum==num){
isLoop=false;
break;
}
start=nowstart-1;
}
start=nowstart;
for(int i=0;i<num;i++){
answer[i]=start;
start--;
}
}
else if(num<total){ //0부터 카운트?
int start=0;
int nowstart=0;
while(isLoop){
int sum=0;
nowstart=start;
for(int i=0;i<num;i++){
sum+=start;
start++;
}
if(sum==total){
isLoop=false;
break;
}
start=nowstart+1;
}
start=nowstart;
for(int i=0;i<num;i++){
answer[i]=start;
start++;
}
}
else if(num>total){
int start=num;
int nowstart=0;
while(isLoop){
int sum=0;
nowstart=start;
for(int i=0;i<num;i++){
sum+=start;
start--;
}
if(sum==total){
isLoop=false;
break;
}
start=nowstart-1;
}
start=nowstart;
for(int i=0;i<num;i++){
answer[i]=start;
start--;
}
}
Arrays.sort(answer);
return answer;
}
}
만약 total
이 0일 때와 num==total
일 때, 그리고 num<total
일 때, num>total
일 때로 나눠서 계산했다.
1. total==0이면, num/2*(-1)부터 시작해서 배열에 넣음
2. num==total이면, num을 시작으로 -1씩해서 합을 계산
3. num<total이면, 0을 기준으로 num개수만큼 total이랑 같은지 비교
4. num>total이면, num을 시작으로 -1씩해서 합을 계산
코딩테스트 입문
을 완료했다!!