코테

99클럽 코테 스터디 3일차 TIL + 백준 31458

pipinstall 2025. 4. 2. 22:44

오늘의 학습 키워드

  • 문제 분석
  • 기능 나누기

[백준 31458 !!초콜릿중독주의!!]

문제 요약

  • 한 줄에 개수
  • 한 줄에 수식
  • 개수만큼 반복해서 한 줄 수식을 계산한다.

해결 방법

팩토리얼과 논리반전을 구분하여 반복해서! 를 줄여나간다.

 

알고리즘:

  1. 수식을 입력받는다.
  2. (숫자!) 또는(! 숫자) 인 패턴을 찾는다.
  3. 해당패턴을을계산하여 리턴하는 함수를 통해 결괏값을 반복적용한다.

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

이렇게 된다는 것을 검증 후에 로직에 적용했다.

Point?

1. 단순 패턴을 찾아 바꾸는 부분?