πŸ“š Notation(ν‘œν˜„μ‹)

πŸ“š Notation(ν‘œν˜„μ‹)

  • μ—°μ‚°μžμ™€ ν”Όμ—°μ‚°μžλ₯Ό μ‘°ν•©ν•˜μ—¬ 값을 μƒμ„±ν•˜λŠ” 식

πŸš€ μ€‘μœ„ ν‘œκΈ°λ²•(Infix Notation)

  • μš°λ¦¬κ°€ 일반적으둜 μ‚¬μš©ν•˜λŠ” 연산식 ν˜•νƒœ
  • A + B 같은 ν˜•νƒœλ‘œ μ—°μ‚°μžκ°€ ν”Όμ—°μ‚°μž 사이에 μœ„μΉ˜
  • μš°μ„ μˆ˜μœ„μ™€ κ΄„ν˜Έλ₯Ό κ³ λ €

βœ… 예제

3 + 5
(2 * 3) + 4
a + b * c

βœ… νŠΉμ§•

  • 가독성이 λ†’μŒ(μ‚¬λžŒν•œν…Œλ§Œ)
  • μ—°μ‚°μž μš°μ„ μˆœμœ„λ₯Ό 고렀해야함
  • κ΄„ν˜Έλ₯Ό μ΄μš©ν•΄ μ—°μ‚° μˆœμ„œλ₯Ό λͺ…ν™•νžˆ ν‘œν˜„ν•΄μ•Ό 함

πŸš€ μ „μœ„ ν‘œκΈ°λ²•(Prefix Notation)

  • μ—°μ‚°μžκ°€ ν”Όμ—°μ‚°μž μ•žμ— μœ„μΉ˜
  • κ΄„ν˜Έκ°€ ν•„μš”ν•˜μ§€ μ•ŠμŒ

βœ… 예제

+ 3 5   (β†’ 3 + 5)
* + 2 3 4  (β†’ (2 + 3) * 4)

βœ… νŠΉμ§•

  • μ—°μ‚°μžμ˜ μœ„μΉ˜κ°€ κ³ μ •λ˜μ–΄ μžˆμ–΄μ„œ μ—°μ‚°μž μš°μ„ μˆœμœ„λ₯Ό κ³ λ €ν•  ν•„μš”μ—†μŒ
  • κ΄„ν˜Έκ°€ ν•„μš”μ—†μŒ
  • 컴퓨터가 μ—°μ‚°ν•˜κΈ°μ— μ ν•©ν•œ ꡬ쑰

πŸš€ ν›„μœ„ ν‘œκΈ°λ²•(Postfix Notation)

  • μ—°μ‚°μžκ°€ ν”Όμ—°μ‚°μž 뒀에 μœ„μΉ˜
  • μŠ€νƒ 을 μ΄μš©ν•˜λ©΄ μ‰½κ²Œ 계산 κ°€λŠ₯

βœ… 예제

3 5 +   (β†’ 3 + 5)
2 3 + 4 *   (β†’ (2 + 3) * 4)

βœ… νŠΉμ§•

  • μ—°μ‚°μž μš°μ„ μˆœμœ„λ₯Ό κ³ λ €ν•  ν•„μš”κ°€ μ—†μŒ
  • κ΄„ν˜Έ 없이도 μ—°μ‚° μˆœμ„œκ°€ λͺ…확함
  • μŠ€νƒμ„ μ΄μš©ν•΄ μ‰½κ²Œ 계산 κ°€λŠ₯

πŸ”‘ μ€‘μœ„ β†’ ν›„μœ„ λ³€ν™˜ (Shunting-yard μ•Œκ³ λ¦¬μ¦˜)

βœ… λ³€ν™˜ κ·œμΉ™

  1. μˆ«μžλŠ” κ·ΈλŒ€λ‘œ 좜λ ₯
  2. μ—°μ‚°μžλŠ” μŠ€νƒμ— μ €μž₯ (μš°μ„ μˆœμœ„ κ³ λ €)
  3. (λŠ” μŠ€νƒμ— push, )λ₯Ό λ§Œλ‚˜λ©΄ (κ°€ λ‚˜μ˜¬ λ•ŒκΉŒμ§€ pop ν›„ 좜λ ₯
  4. λͺ¨λ“  μ—°μ‚°μž pop ν›„ 좜λ ₯
#include <iostream>
#include <stack>
#include <cctype>
using namespace std;

int precedence(char op) {
    if (op == '+' || op == '-') return 1;
    if (op == '*' || op == '/') return 2;
    return 0;
}

string infixToPostfix(string infix) {
    stack<char> stk;
    string postfix = "";

    for (char ch : infix) {
        if (isdigit(ch)) {
            postfix += ch;
            postfix += ' ';
        } 
        else if (ch == '(') stk.push(ch);
        else if (ch == ')') {
            while (!stk.empty() && stk.top() != '(') {
                postfix += stk.top();
                postfix += ' ';
                stk.pop();
            }
            stk.pop();  // '(' 제거
        }
        else {  // μ—°μ‚°μž
            while (!stk.empty() && precedence(stk.top()) >= precedence(ch)) {
                postfix += stk.top();
                postfix += ' ';
                stk.pop();
            }
            stk.push(ch);
        }
    }
    while (!stk.empty()) {
        postfix += stk.top();
        postfix += ' ';
        stk.pop();
    }
    return postfix;
}

int main() {
    string infix = "(2+3)*4";
    cout << infixToPostfix(infix);  // 좜λ ₯: 2 3 + 4 *
}