코딩테스트/JavaScript

[코딩테스트] 후위식 연산(postfix)

CODE_PLAN 2024. 1. 7. 20:34

나의 풀이

function solution(s) { 
             let's answer ; 
            stack = []; 
            // stack.push( '+' ) 
            // answer = if (str.includes( '+' || '*' || "/" || "-" )) { 
                answer.push() 
            } 
            return answer ; 
        } for ( let i=0; i<str.length; i++){ 
              if (str.includes( '+' || '*' || "/" || "-" )) { 
                answer.push() 
            } 
        } 
        str = "352+*9-" ; 
        console.log(str[]) 
        console.log(solution(str));
            

        

모범 답안

   function solution(s){  
                let answer;
                let stack=[];
                for(let x of s){
                    if(!isNaN(x)) stack.push(Number(x));
                    else{
                        let rt=stack.pop();
                        let lt=stack.pop();
                        if(x==='+') stack.push(lt+rt);
                        else if(x==='-') stack.push(lt-rt);
                        else if(x==='*') stack.push(lt*rt);
                        else if(x==='/') stack.push(lt/rt);
                    }
                }
                answer=stack[0];
                return answer;
            }

            let str="352+*9-";
            console.log(solution(str));