오늘의 학습 키워드
- 문제 분석
- 기능 나누기
[백준 31458 !!초콜릿중독주의!!]
문제 요약
- 한 줄에 개수
- 한 줄에 수식
- 개수만큼 반복해서 한 줄 수식을 계산한다.
해결 방법
팩토리얼과 논리반전을 구분하여 반복해서! 를 줄여나간다.
알고리즘:
- 수식을 입력받는다.
- (숫자!) 또는(! 숫자) 인 패턴을 찾는다.
- 해당패턴을을계산하여 리턴하는 함수를 통해 결괏값을 반복적용한다.
Java 코드 구현
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
for(int i = 0; i < n; i++) {
System.out.println(calc(sc.nextLine()));
}
}
public static int calc(String text) {
String result = text;
while(result.contains("!")) {
result = calcP(result);
result = calcL(result);
}
return Integer.parseInt(result);
}
public static String calcP(String text) {
Pattern pattern = Pattern.compile("([01])(!+)");
Matcher matcher = pattern.matcher(text);
if(matcher.find()) {
return text.substring(0, matcher.start()) + 1 +
text.substring(matcher.end());
}
return text;
}
public static String calcL(String text) {
Pattern pattern = Pattern.compile("(!+)([01])");
Matcher matcher = pattern.matcher(text);
if(matcher.find()) {
int notCount = matcher.group(1).length();
int num = Integer.parseInt(matcher.group(2));
int notResult = logicalNot(num, notCount);
return text.substring(0, matcher.start()) + notResult +
text.substring(matcher.end());
}
return text;
}
public static int logicalNot(int n, int times) {
return (times % 2 == 1) ? (1 - n) : n;
}
}
오늘의 회고
What?
반복문안에서 특정패턴을 찾아 바꾼다.
How?
반복되는 부분과 패턴을 파악하려고 생각했고
!!1!!
!!1!
!!1
!0
1
이렇게 된다는 것을 검증 후에 로직에 적용했다.
Point?
1. 단순 패턴을 찾아 바꾸는 부분?
'코테' 카테고리의 다른 글
99클럽 코테 스터디 9일차 TIL + 백준 3986 (1) | 2025.04.08 |
---|---|
99클럽 코테 스터디 8일차 TIL + [LeetCode 70번] Climbing Stairs (1) | 2025.04.07 |
99클럽 코테 스터디 4일차 TIL + [LeetCode 232번] Implement Queue using Stacks (0) | 2025.04.03 |
99클럽 코테 스터디 2일차 TIL + 백준 10820 (0) | 2025.04.01 |
99클럽 코테 스터디 1일차 TIL + 백준 1032 (0) | 2025.03.31 |