역폴란드 표기법 평가

bong bong·2023년 9월 1일

알고리즘

목록 보기
18/31

문제

역 폴란드 표기법tokens 의 산술 표현식을 나타내는 문자열 배열이 제공됩니다 .

표현을 평가해 보세요. 표현식의 값을 나타내는 정수를 반환합니다 .

참고 사항:

유효한 연산자는 '+', '-', '*'및 입니다 '/'.
각 피연산자는 정수이거나 다른 표현식일 수 있습니다.
두 정수 사이의 나눗셈은 항상 0을 향해 잘립니다 .
0으로 나누는 일은 없을 것입니다.
입력은 역방향 폴란드어 표기법으로 유효한 산술 표현식을 나타냅니다.
답과 모든 중간 계산은 32비트 정수로 표현될 수 있습니다

구현 방식

스택에 하나씩 입력을 받아서 만약 연산을 만나면 연산해볼까??!?

연산선정

switch (operator) {
            case "+":
                return operand1 + operand2;
            case "-":
                return operand1 - operand2;
            case "*":
                return operand1 * operand2;
            case "/":
                return operand1 / operand2;
            default:
                throw new IllegalArgumentException("Invalid operator: " + operator);
        }

연산 으로 만들기

private boolean isOperator(String token) {
return token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/");
}

소스코드

 Stack<Integer> stack = new Stack<>();
        
        for (String token : tokens) {
            if (isOperator(token)) {
                int operand2 = stack.pop();
                int operand1 = stack.pop();
                int result = performOperation(operand1, operand2, token);
                stack.push(result);
            } else {
                stack.push(Integer.parseInt(token));
            }
        }
        
        return stack.pop();
    }
    
    private boolean isOperator(String token) {
        return token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/");
    }
    
    private int performOperation(int operand1, int operand2, String operator) {
        switch (operator) {
            case "+":
                return operand1 + operand2;
            case "-":
                return operand1 - operand2;
            case "*":
                return operand1 * operand2;
            case "/":
                return operand1 / operand2;
            default:
                throw new IllegalArgumentException("Invalid operator: " + operator);
        }
profile
let's go invent tomorrow rather than worrying about what happened yesterday - Steven Paul Jobs

0개의 댓글