반응형
주사위 게임 3
문제 설명



요구사항
- 모든 숫자가 같다면 a * 1111
- 세개가 같고(a,b,c) 하나만(d) 다르다면 (10 * a + d)^2
- 두개 씩 같다면 a + b * |a - b|
- 두개가 같고(a,b) 나머지 둘이 서로 다르다면(c, d) c * d
- 모든 숫자가 다르다면 가장 작은 숫자
테스트
package lv0;
import java.util.TreeMap;
public class 주사위_게임_3 {
public int solution(int a, int b, int c, int d) {
int answer = 1;
// 키의 값으로 정렬된 map
TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
// map에 숫자별 출현 빈도 저장
map.put(a, map.getOrDefault(a, 0) + 1);
map.put(b, map.getOrDefault(b, 0) + 1);
map.put(c, map.getOrDefault(c, 0) + 1);
map.put(d, map.getOrDefault(d, 0) + 1);
// 모든 수가 같다면
if(map.size() == 1) {
answer = 1111 * a;
}
// 숫자가 두 종류(3개가 같고 하나가 다르거나 두개씩 같은 경우)
if(map.size() == 2) {
int[] arr = new int[2];
int index = 0;
int one = -1;
int three = -1;
for (Integer key : map.keySet()) {
arr[index++] = key;
// 3개가 같은 숫자
if(map.get(key) == 3) {
three = key;
}
if(map.get(key) == 1) {
one = key;
}
}
// 3개가 같은 숫자가 존재하는경우
if(three == -1) {
answer = (arr[0] + arr[1]) * Math.abs(arr[0] - arr[1]);
} else {
answer = (10 * three + one) * (10 * three + one);
}
}
// 두개가 같고 하나씩 다른 경우
if(map.size() == 3) {
int[] arr = new int[2];
int index = 0;
for (Integer key : map.keySet()) {
if(map.get(key) == 1) {
arr[index++] = key;
}
}
answer = arr[0] * arr[1];
}
// 모두 다른 경우
if(map.size() == 4) {
answer = map.firstKey();
}
return answer;
}
}
프로그래머스
import java.util.TreeMap;
class Solution {
public int solution(int a, int b, int c, int d) {
int answer = 1;
TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
map.put(a, map.getOrDefault(a, 0) + 1);
map.put(b, map.getOrDefault(b, 0) + 1);
map.put(c, map.getOrDefault(c, 0) + 1);
map.put(d, map.getOrDefault(d, 0) + 1);
if(map.size() == 1) {
answer = 1111 * a;
}
if(map.size() == 2) {
int[] arr = new int[2];
int index = 0;
int one = -1;
int three = -1;
for (Integer key : map.keySet()) {
arr[index++] = key;
if(map.get(key) == 3) {
three = key;
}
if(map.get(key) == 1) {
one = key;
}
}
if(three == -1) {
answer = (arr[0] + arr[1]) * Math.abs(arr[0] - arr[1]);
} else {
answer = (10 * three + one) * (10 * three + one);
}
}
if(map.size() == 3) {
int[] arr = new int[2];
int index = 0;
for (Integer key : map.keySet()) {
if(map.get(key) == 1) {
arr[index++] = key;
}
}
answer = arr[0] * arr[1];
}
if(map.size() == 4) {
answer = map.firstKey();
}
return answer;
}
}
결과


반응형
'코딩테스트 > 프로그래머스 Lv. 0' 카테고리의 다른 글
| [프로그래머스] Lv. 0 9로 나눈 나머지 JAVA (0) | 2025.02.15 |
|---|---|
| [프로그래머스] Lv. 0 글자 이어 붙여 문자열 만들기 JAVA (0) | 2025.02.15 |
| [프로그래머스] Lv. 0 간단한 논리 연산 JAVA (1) | 2025.02.06 |
| [프로그래머스] Lv. 0 배열 만들기 4 JAVA (0) | 2025.02.06 |
| [프로그래머스] Lv. 0 콜라츠 수열 만들기 JAVA (1) | 2025.02.04 |