1233. [S/W 문제해결 기본] 9일차 - 사칙연산 유효성 검사
사칙연산과 양의 정수로만 구성된 임의의 이진 트리가 주어질 때, 이 식의 유효성을 검사해서 출력하라.
처음에는 [SWEA] 1232. 사칙연산 문제를 활용해서 풀려고 시도했다. 그런데 이 문제는 유효성만 검사하는 것이므로 전혀 달랐다! 연산자임을 판별하는 isDigit()
은 활용할 수 있었다.
입력을 받을 때마다 유효한지 검사했다. (boolean타입변수 answer
이용)
입력 데이터의 개수가 가변적이므로 sc.nextLine()
을 이용했다! 굳굳
그런데 N은 sc.nextInt()
로 받았더니 개행문자때문에 nextLine()
을 해줘야돼서 N도 sc.nextLine()
으로 받았다.
import java.util.Scanner;
import java.io.FileInputStream;
class Solution
{
static boolean answer = true;
public static void main(String args[]) throws Exception
{
Scanner sc = new Scanner(System.in);
int T = 10;
for(int test_case = 1; test_case <= T; test_case++)
{
answer = true;
String n = sc.nextLine();
int N = Integer.parseInt(n);
input(N, sc);
System.out.printf("#%d %d\n", test_case, answer==true?1:0);
}
}
static void input(int N, Scanner sc) {
int a;
String b;
int i;
String str;
for (i=1; i<=N; i++) {
str = sc.nextLine(); // 한 줄씩 입력받기
String [] arr = str.split(" "); // 띄어쓰기로 구분
if (arr.length == 2) { // 단말노드이므로 숫자여야만 함
if (!isDigit(arr[1].charAt(0))) answer = false;
} else { // 자식이 있는 경우
// 연산자 여야 함..
if (isDigit(arr[1].charAt(0))) answer = false;
// 숫자여야 함..
if (!isDigit(arr[2].charAt(0))) answer = false;
if (arr.length == 4 && !isDigit(arr[3].charAt(0))) answer = false;
}
}
}
static boolean isDigit(char t) {
if (t=='/' || t=='+'||t=='-'||t=='*') return false;
return true;
}
}
input()
함수에서 유효하지 않다 싶으면 바로 return false;
해버림; -> 입력은 다 받아야 한다.