코딩테스트
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
내가 제출한 코드
public class Main {
public static void main(String[] args) {
int[][] arr = {
{60, 50},
{30, 70},
{60, 30},
{80, 40}
};
System.out.println(solution(arr));
}
public static int solution(int[][] sizes) {
int answer = 0;
int index = 0;
int max = 0;
int a = 0;
int b = 0;
// 1. 가로 혹은 세로 중 가장 큰 숫자를 기준으로 숫자 위치를 수정하기
for (int[] size : sizes) {
for (int i = 0; i < size.length; i++) {
if (size[i] > max) {
max = size[i];
index = i;
}
}
}
// 2. 큰 숫자가 존재하는 인덱스 위치와 동일하게 각 배열 안의 숫자들의 위치를 수정하기
for (int[] size : sizes) {
int temp = 0;
if (index == 0) {
if (size[index] < size[index + 1]) {
temp = size[index];
size[index] = size[index + 1];
size[index + 1] = temp;
}
} else {
if (size[index] < size[index - 1]) {
temp = size[index];
size[index] = size[index - 1];
size[index - 1] = temp;
}
}
}
// 3. 가로와 세로에서 가장 큰 숫자 저장하기
for (int[] size : sizes) {
if (a < size[0]) {
a = size[0];
}
if (b < size[1]) {
b = size[1];
}
}
answer = a * b;
return answer;
}
}
다시 정리한 코드
class Solution {
public int solution(int[][] sizes) {
int maxWidth = 0;
int maxHeight = 0;
for (int[] size : sizes) {
int width = Math.min(size[0], size[1]);
int height = Math.max(size[0], size[1]);
maxWidth = Math.max(maxWidth, width);
maxHeight = Math.max(maxHeight, height);
}
return maxWidth * maxHeight;
}
}
시저 암호
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
제출한 코드
class Solution {
public String solution(String s, int n) {
StringBuilder answer = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isUpperCase(c)) {
// 'A'의 ASCII 코드는 65
char shifted = (char) ((c - 'A' + n) % 26 + 'A');
answer.append(shifted);
} else if (Character.isLowerCase(c)) {
// 'a'의 ASCII 코드는 97
char shifted = (char) ((c - 'a' + n) % 26 + 'a');
answer.append(shifted);
} else {
// 공백 등 알파벳이 아닌 경우 그대로 추가
answer.append(c);
}
}
return answer.toString();
}
}
영문 대소문자에 모듈 연산(%)을 적용하여 영문 대소문자 범위 안에서 순환적인 코드를 구현했다.
예1) 거리 n은 2이며 대문자 A를 입력한다고 가정하자.
- 65 - 'A' + 2 = 2 // 'A' == 65 (아스키 코드)
- 2 % 26 = 2 // 2가 26보다 작으므로 나머지는 2
- 2 + 'A' = 67 // 67 == 'C'
예2) 거리 n은 1이며 소문자 z를 입력한다고 가정하자.
- 122 - 'a' + 1 = 26
- 26 % 26 = 0
- 0 + 'a' = 97 // 97 == 'a'
댓글