Notice
Recent Posts
Recent Comments
Link
Star_project
CosPro JAVA 1급 기출 1회 문제2 본문
#문제2
다음과 같이 n x n 크기의 격자에 1부터 n x n까지의 수가 하나씩 있습니다.
이때 수가 다음과 같은 순서로 배치되어있다면 이것을 n-소용돌이 수라고 부릅니다.
소용돌이 수에서 1행 1열부터 n 행 n 열까지 대각선상에 존재하는 수들의 합을 구해야 합니다.
위의 예에서 대각선상에 존재하는 수의 합은 15입니다.
격자의 크기 n이 주어질 때 n-소용돌이 수의 대각선상에 존재하는 수들의 합을 return 하도록 solution 메소드를 완성해주세요.
매개변수 설명
격자의 크기 n이 solution 메소드의 매개변수로 주어집니다.
- n은 1 이상 100 이하의 자연수입니다.
return 값 설명
n-소용돌이 수의 대각선상에 존재하는 수들의 합을 return 해주세요.
예시
n | return |
---|---|
3 | 15 |
2 | 4 |
예시 설명
예시 #1
문제의 예와 같습니다.
예시 #2
1과 3을 더하여 4가 됩니다.
// You may use import as below.
//import java.util.*;
class Solution {
public int solution(int n) {
// Write code here.
int answer = 0;
return answer;
}
// The following is main method to output testcase.
public static void main(String[] args) {
Solution sol = new Solution();
int n1 = 3;
int ret1 = sol.solution(n1);
// Press Run button to receive output.
System.out.println("Solution: return value of the method is " + ret1 + " .");
int n2 = 2;
int ret2 = sol.solution(n2);
// Press Run button to receive output.
System.out.println("Solution: return value of the method is " + ret2 + " .");
}
}
// You may use import as below.
class Solution {
public int solution(int n) {
// Write code here.
int[][] array = new int[n][n];
/*for (int i=0; i < array.length; i++){
System.out.println(Arrays.toString(array[i]));
}*/
int dir=0;
int loop=n;
int r=0;
int c=-1;
int num=0;
int[] dr={0, 1, 0, -1};
int[] dc={1, 0, -1, 0};
while (num<n*n){
for(int i=0;i<loop;i++){
r+=dr[dir];
c+=dc[dir];
num+=1;
array[r][c]=num;
}
dir=(dir+1)%4;
if(dir%2==1) loop-=1;
}
int answer = 0;
for(int x=0;x<n;x++){
answer+=array[x][x];
}
return answer;
}
// The following is main method to output testcase.
public static void main(String[] args) {
Solution sol = new Solution();
int n1 = 3;
int ret1 = sol.solution(n1);
// Press Run button to receive output.
System.out.println("Solution: return value of the method is " + ret1 + " .");
int n2 = 2;
int ret2 = sol.solution(n2);
// Press Run button to receive output.
System.out.println("Solution: return value of the method is " + ret2 + " .");
}
}
Solution: return value of the method is 15 .
Solution: return value of the method is 4 .
'코딩테스트 > JAVA' 카테고리의 다른 글
CosPro JAVA 1급 기출 1회 문제4 (0) | 2022.06.10 |
---|---|
CosPro JAVA 1급 기출 1회 문제3 (0) | 2022.06.10 |
CosPro JAVA 1급 기출 1회 문제1 (0) | 2022.06.09 |
CosPro JAVA 2급 기출 2회 문제10 (0) | 2022.06.09 |
CosPro JAVA 2급 기출 2회 문제9 (0) | 2022.06.09 |