/* 연속된 수의 합
연속된 세 개의 정수를 더해 12가 되는 경우는 3, 4, 5입니다.
두 정수 num과 total이 주어집니다.
연속된 수 num개를 더한 값이 total이 될 때,
정수 배열을 오름차순으로 담아 return하도록 solution함수를 완성해보세요.
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입니다.
*/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | public class programmer_0_3 { static int a = 3; static int a1 = 12; static int b = 5; static int b1 = 15; static int c = 4; static int c1 = 14; static int d = 5; static int d1 = 5; public int[] solution(int num, int total) { int[] answer = new int[num]; //java.lang.ArrayIndexOutOfBoundsException 방지(배열길이 설정) int chk = num%2; //구분자 if(chk == 0){ //짝수개(끝에서부터 감소) for(int i=num-1; i>=0; i--){ if(i == num-1) answer[i] = total/num + total%num; else answer[i] = answer[i+1] - 1; } } else{ //홀수개(앞에서부터 증가) for(int i=0; i<num; i++){ if(i == 0) answer[i] = total/num - num/2; else answer[i] = answer[i-1] + 1; } } for(int i=0; i<answer.length; i++){ //결과확인 System.out.println("i = " + i + " / " + answer[i]); } return answer; } public static void main(String[] args){ programmer_0_3 t = new programmer_0_3(); // System.out.println("result = " + t.solution(a,a1)); // System.out.println("---------------------------------------"); // System.out.println("result2 = " + t.solution(b,b1)); System.out.println("---------------------------------------"); System.out.println("result3 = " + t.solution(c,c1)); System.out.println("---------------------------------------"); // System.out.println("result4 = " + t.solution(d,d1)); // System.out.println("---------------------------------------"); } } | cs |