์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[์ธํ”„๋Ÿฐ ์„น์…˜6] ํ›„์œ„์‹ ์—ฐ์‚ฐ postfix (Javascript)

์€์ง„ 2021. 6. 27. 01:45

์ธํ”„๋Ÿฐ

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[์ธํ”„๋Ÿฐ ์„น์…˜6] ํ›„์œ„์‹ ์—ฐ์‚ฐ postfix (Javascript)
์œ ๋ฃŒ ๊ฐ•์˜์ธ ๊ด€๊ณ„๋กœ ๋ฌธ์ œ ์„ค๋ช…์€ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.


โœ๏ธIdea Sketch

2021-06-27

1. str์˜ ์›์†Œ๋ฅผ ๋ฐ˜๋ณต

for (let x of str) {

}

2. x๊ฐ€ ์ˆซ์ž๋ฉด stack.push();

3. x๊ฐ€ ์—ฐ์‚ฐ๊ธฐํ˜ธ๋ฉด stack.pop(); ๋กœ ์ˆซ์ž๋ฅผ ๊บผ๋‚ด์˜จ ํ›„ stack[stack.length-1] ๊ณผ ์—ฐ์‚ฐ

4. isNaN(s) ์‚ฌ์šฉ

  • s์ด ์ˆซ์ž๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ true ๋ฆฌํ„ด
if (isNaN(x)) {
    let n = stack.pop();
    if (x === '+') stack[stack.length-1] += n;
    else if (x === '-') stack[stack.length-1] -= n;
    else if (x === '*') stack[stack.length-1] *= n;
    else if (x === '/') stack[stack.length-1] /= n;
}
else stack.push(x);

5. ๋ฌธ์ž์—ด '5'๋ฅผ ์ˆซ์ž 5๋กœ ์ „ํ™˜ํ•ด์•ผํ•จ

  • stack.push(); ํ•  ๋•Œ ์ฒ˜๋ฆฌ
  • ๋ฐฉ๋ฒ• 1 : Number('5');
  • ๋ฐฉ๋ฒ• 2 : parseInt('5');
stack.push(paseInt(x));


โœ๏ธ์†Œ์Šค์ฝ”๋“œ

2021-06-27

function solution(str) {
    let stack = [];

    for (let x of str) {
        if (isNaN(x)) {
            let n = stack.pop();
            if (x === '+') stack[stack.length - 1] += n;
            else if (x === '-') stack[stack.length - 1] -= n;
            else if (x === '*') stack[stack.length - 1] *= n;
            else if (x === '/') stack[stack.length - 1] /= n;
        }
        else stack.push(parseInt(x));
    }

    return stack.pop();
}