코딩테스트

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

dackyy 2022. 7. 14. 16:08
반응형

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;
public class InStackCalc {
    static String str = "113 + 11 - (32 - (9 - 2 + 6)) + (32 - (9 - 2 + 6))";
    static String[] arr = str.split("");
    static int cnt;
    static String[] stack = new String[str.length()];
    static String postfix = "";

    public static void main(String[] args) {
        //후위표기법으로 저장
        cnt = 0;
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
            if (StringUtils.isNumeric(arr[i])) {
                postfix += arr[i];
            } else if (arr[i].equals(" "))
                postfix += arr[i];

            else if (arr[i].equals("(")) {
                push(arr[i]);
            } else if (arr[i].equals(")")) {
                for (int k = 0; k < stack.length; k++) {
                    System.out.print(stack[k]);
                }
                do {
                postfix += " ";
                postfix += pop();
            } while (!stack[cnt].equals("("));
                postfix += pop();
            } else {
                if (cnt == 0)
                    push(arr[i]);
                else if (stack[cnt - 1].equals("+") || stack[cnt - 1].equals("-")) {
                    postfix += pop();
                    push(arr[i]);
                } else {
                    push(arr[i]);
                }
            }
        }
        postfix = postfix.replace("  ", " ");
        postfix = postfix.replace("(", "");
        System.out.println(postfix);

        //계산시작
        stack = new String[str.length()];
        cnt = 0;
        String[] sStack = postfix.split(" ");
        for (int i = 0; i < sStack.length; i++) {
            if (StringUtils.isNumeric(sStack[i]))
                push(sStack[i]);

            else if (sStack[i].equals("+"))
                push(Integer.toString(Integer.parseInt(pop()) + Integer.parseInt(pop())));

            else if (sStack[i].equals("-"))
                push(Integer.toString(-Integer.parseInt(pop()) + Integer.parseInt(pop())));
        }
        System.out.println(str + " = " + stack[0]);

    }
    static String pop(){
        if(cnt == 0){
            return null;
        }
        else{
            int tmp = cnt-1;
            System.out.println("pop : " + stack[tmp]);
            cnt--;
            return stack[tmp];
        }
    }
    static void push(String num){
        System.out.println("push : " + num);
        if (cnt == 0){
            stack[0] = num;
        }
        else {
            stack[cnt] = num;
        }
        cnt++;
    }
}
반응형