✨
Saltberry
GithubLinkedIn
  • 개요 Overview
  • 📝HTML/CSS
    • 구조 HTML
    • 스타일 CSS
      • z-index
  • 📦개발 Development
    • 개발 Implementation
    • 단어 Glosarry
    • 깃 Git
    • 해시 Hash
    • 노드 패키지 매니저 Node Package Manager
    • 브라우저 랜더링 Browser Rendering Process
    • 교차 출처 리소스 공유 CORS
    • 인터프리터 Interpreter
    • Object-oriented programming(OOP) 객체지향 프로그래밍
  • 💡CS 50
    • Computational Thinking
  • ✨자바스크립트 Javascript
    • 자바스크립트란 What is JavaScript
    • 표현식과 문 Expression Statement
    • 변수 Variable
    • 함수 Function
    • 참과 거짓 값 Truth Falsy
    • 배열 Array
    • Import Export
    • 스택과 큐 Stack Queue
    • 문서객체모델 Document Object Model
      • 개요 Overview
      • 도큐먼트 Document
      • HTMLCollection
      • getMethod
      • NodeList
      • childNodes, children
      • Event
      • live, static
      • Element
      • DOM Token
      • 속성 attribute
      • implementation
      • 노드 Node
      • HTMLElement
    • 브라우저 저장소 Cookie Web Storage
  • 🎁리액트 React
    • 리액트 톧아보기 Overview
    • Intro
      • 상태의 불변성 State Immutability
      • Props and State
      • Hooks
    • Concepts
  • 🚦타입스크립트 Typescript
    • Page 1
  • 🗃️리덕스 Redux
    • 왜 리덕스를 사용할까 Why Redux
    • 플럭스 Flux
  • 📬넥스트 Nextjs
    • Pages
  • ✅면접 Interview
    • Index
    • Implement experiences
    • Best practice for query parameter and fetch
  • 🚀TECH
    • Lists
    • Zustand
  • 🧬Algorithm
    • Types of algorithms
    • 이진수 변환 Binary Number
    • 후위 연산자 Postfix expression
    • 선택 정렬 Selection Sort
    • Find longest substring without repeating characters
    • 올바른 괄호 Valid Parentheses
  • 📔Mathematics
    • 다항식 Polynomial
  • 🗂️Database
    • 데이터베이스 Database
  • 📝Class
    • 자료구조 Data Structure
      • 배열 Array
    • C++ 프로그래밍
      • C++ 기초
    • 소프트웨어 공학 Software engineering
      • 소프트웨어 개요 Software overview
      • 소프트웨어 프로세스 Software process
    • 자바 Java
      • 자바와 객체지향 프로그래밍 Java and OOP(Object-oriented programming)
  • Java
    • 자바가 뭐지?
  • CA EI
    • CA EI
Powered by GitBook
On this page
  1. Algorithm

후위 연산자 Postfix expression

function solution(value) {
    const str = value.replace(/ /g, "").split('');
    let postfix = "";
    const operatorStack = [];
    const operatorPriority = {
        '(': 0,
        '+': 1,
        '-': 1,
        '*': 2,
        '/': 2,

    };

    for (let i = 0; i < str.length; i++) {
        if (!isNaN(+str[i])) {
            postfix += str[i];

        } else {
            if (!operatorStack.length) {
                operatorStack.push(str[i]);

            } else {
                if (operatorPriority[str[i]] >= operatorPriority[operatorStack[operatorStack.length - 1]]) {
                    operatorStack.push(str[i]);
                } else {
                    while (operatorStack[operatorStack.length - 1] === '(' || operatorStack.length) {
                        postfix += operatorStack.pop();
                    };
                    if(operatorStack[operatorStack.length - 1] === '(') {
                        delete operatorStack[operatorStack.length - 1];
                    }
                    operatorStack.push(str[i]);
                }
            }
        }

    }
    while(operatorStack.length) {
        postfix += operatorStack.pop();
    }

    const calculateStack = [];


    for(let i = 0; i < postfix.length; i++) {
        if(!isNaN(+postfix[i])) {
            calculateStack.push(+postfix[i])
        }
        else {
            const right = calculateStack.pop();
            const left = calculateStack.pop();

            switch (postfix[i]) {
                case "+":
                    calculateStack[calculateStack.length] = left + right;
                    break
                case "-":
                    calculateStack[calculateStack.length] = left - right;
                    break
                case "*":
                    calculateStack[calculateStack.length] = Math.ceil(left * right);
                    break
                case "/":
                    calculateStack[calculateStack.length] = Math.ceil(left / right);
                    break
            }

        }

    }
    return calculateStack[0];
}


console.log(solution("3 * (3 - 1) + 2") === 8)

// console.log(solution("1 + 1") === 2)
// console.log(solution("4/2+2") === 4)
// console.log(solution("3/2+1") === 3)
// console.log(solution(" 2+3*1  -1 ") === 4)
// console.log(solution("2+ 3* 1") === 5)

Last updated 1 year ago

🧬