카테고리 없음

[1233] 사칙연산 유효성 검사 in Java

여니's 2022. 8. 9. 17:25

 

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV141176AIwCFAYD 

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com


접근 방식

본인 위치, 연산자, 왼쪽 자식노드, 오른쪽 자식 노드
본인 위치, 숫자

 

위와 같이 입력이 되었을 때 1 출력

 

 

시행 착오

- hasMoreTokens() 사용법을 몰라서 헤맸던 문제

위 메소드는 StringTokenizer에 사용할 수 있는 토큰이 있는지 확인하는 메소드!

만약 존재한다면 true, 존재하지 않는다면  false를 반환한다.

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Solution {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        for (int k = 1; k <= 10; k++) {			
            int N= Integer.parseInt(br.readLine());
            int isPossible=1;
            for (int n = 0; n < N; n++) {
                StringTokenizer st = new StringTokenizer(br.readLine());
                int number=Integer.parseInt(st.nextToken());
                char operatorOrNum=st.nextToken().charAt(0);

                // 최대 2개까지 올 수 있는 상황
                // 1. 자식노드가 1개라도 있는 경우 -> operatorOrNum이 숫자면 잘못된 트리
                // 2. 자식노드가 0개인 경우 -> operatorOrNum이 연산자면 잘못된 트리

                if(st.hasMoreTokens()) { // 1. 자식노드가 1개라도 있는 경우			
                    if (operatorOrNum>='0' && operatorOrNum<='9') {
                        //  operatorOrNum이 숫자면 잘못된 트리
                        isPossible=0;
                    }
                }else { // 2. 자식노드가 0개인 경우
                    if (!(operatorOrNum>='0' && operatorOrNum<='9')) {
                        // operatorOrNum이 연산자면 잘못된 트리
                        isPossible=0;
                    }
                }
            }
            System.out.print("#"+k+" "+isPossible+"\n");
                }
            }
}
/*
본인 위치, 연산자, 왼쪽 자식노드, 오른쪽 자식 노드
본인 위치, 숫자, 왼쪽 자식노드, 오른쪽 자식 노드 
*/