코딩테스트

[JAVA] 후위연산자를 이용한 + - 연산 (제네릭 Stack 사용)

dackyy 2022. 7. 14. 18:46
반응형

import org.apache.commons.lang3.StringUtils; 함수를 사용하려면 apache 홈페이지에서 api를 다운받으셔야합니다.

StringUtils.inNumeric( ) -> 매개변수가 숫자인지 아닌지 boolean값으로 리턴을 해줍니다.

다운로드 링크  https://commons.apache.org/proper/commons-lang/download_lang.cgi

다운 받으신 후 사용하시는 IDE에서 외부라이브러리 추가 하시고 사용하시면 됩니다.

package Day2;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
public class PostFix {
    static String str = "113 + 11 - (32 - (9 - 2 + 6)) + (32 - (9 - 2 + 6))";
    static String[] items = str.split("");
    static ArrayList<String> postFixes = new ArrayList<String>(Arrays.asList(items));
    static Stack<String> stack = new Stack<String>();
    static Stack<Integer> calcul = new Stack<Integer>();
    public static void main(String[] args) {
        System.out.println("중위 표기법 \n113 + 11 - (32 - (9 - 2 + 6)) + (32 - (9 - 2 + 6))");
        String postfix = "";
        for (String  element: postFixes) {
            if (StringUtils.isNumeric(element)) {
                postfix += element;
            }
            else if (element.equals("("))
                stack.push(element);
            else if (element.equals(")")) {
                while (!stack.peek().equals("("))
                    postfix += " " +stack.pop();
                stack.pop();
            }
            else if(element.equals(" "))
                postfix += " ";
            else{
                if(!stack.empty()) {
                    if(stack.contains("(")) {
                        while (!stack.peek().equals("(")) {
                            postfix += stack.pop();
                        }
                    }
                    else
                        postfix += stack.pop();
                }
                    stack.push(element);
            }
        }
        if (stack.size() == 1)
            postfix += " " + stack.pop();
        postfix = postfix.replace("  ", " ");

        System.out.println("후위표기법\n"+postfix);
        String[] calc = postfix.split(" ");
        for(int i = 0; i < calc.length; i++) {
            if(StringUtils.isNumeric(calc[i]))
                calcul.push(Integer.parseInt(calc[i]));
            else if(calc[i].equals("+"))
                calcul.push(calcul.pop() + calcul.pop());
            else
                calcul.push(-calcul.pop() + calcul.pop());
        }
        System.out.println("답 = " + calcul);
    }
}
반응형