https://school.programmers.co.kr/learn/courses/30/lessons/42842
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
풀이
import java.io.*;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] answer;
int brown = Integer.parseInt(br.readLine()); // 8<=brown<=5000
int yellow = Integer.parseInt(br.readLine()); // 1<=yellow<=2000000
// 카펫의 전체 면적
int total = brown + yellow;
// 가로와 세로의 길이는 total의 약수여야함.
// total의 약수는 total의 제곱근(Math.sqrt(total))까지만 탐색하면, 약수는 대칭적이기 때문에 모든 약수에 대해 탐색할 수 있다.
// ex) total = 12일때 (1,12)(2,6)(3,4)|(4,3)(6,2)(12,1)로 대칭
// 가로길이가 세로길이보다 길어야하기 때문에, for문의 변수를 height로 지정하여 탐색
for (int height = 1; height <= Math.sqrt(total); height++) {
// height가 total의 약수일 경우
if (total % height == 0) {
int width = total / height;
if ((width-2)*(height-2) == yellow) {
answer = new int[]{width, height};
System.out.println(Arrays.toString(answer));
}
}
}
}
}
제출
class Solution {
public int[] solution(int brown, int yellow) {
// 카펫의 전체 면적
int total = brown + yellow;
// 가로와 세로의 길이는 total의 약수여야함.
// total의 약수는 total의 제곱근(Math.sqrt(total))까지만 탐색하면,
// 약수는 대칭적이기 때문에 모든 액수에 대해 탐색할 수 있다.
// ex) total = 12일때 (1,12)(2,6)(3,4)|(4,3)(6,2)(12,1)로 대칭
// 가로길이가 세로길이보다 길어야하기 때문에, for문의 변수를 height로 지정하여 탐색
for (int height = 1; height <= Math.sqrt(total); height++) {
// height가 total의 약수일 경우
if (total % height == 0) {
int width = total / height;
// yellow 조건에 맞는지 확인
if ((width-2)*(height-2) == yellow) {
return new int[]{width, height}; // [가로,세로] 배열 반환
}
}
}
return new int[]{};
}
}
'Algorithm Solving > Java' 카테고리의 다른 글
[programmers] Java Lv.2 - N개의 최소공배수 (1) | 2025.01.07 |
---|---|
[programmers] Java Lv.2 - 예상 대진표 (0) | 2025.01.06 |
[BOJ] 백준 9095번 : 1, 2, 3 더하기 - Java (0) | 2025.01.02 |
[BOJ] 백준 1181번 : 단어 정렬 - Java (0) | 2025.01.01 |
[BOJ] 백준 14226번 : 이모티콘 - Java (0) | 2024.12.31 |