function calculation(stack, s, aws){
let v = stack.pop();
if(s === "+") aws += v;
else if(s === "-") aws -= v;
else if(s === "*") aws *= v;
else aws /= v;
return aws;
}
function solution(s){
let answer = 0,
stack =[],
sta = true;
for(let s of str) {
if(s.charCodeAt(0)>47 && s.charCodeAt(0)<58){
stack.push(s*1);
sta = true;
}else {
if(sta === true){
for(let i =0; i<stack.length; i++){
if(answer === 0) answer = stack.pop();
else answer = calculation(stack, s, answer);
}
sta = false;
}else answer = calculation(stack, s, answer);
}
console.log("stack:",stack,"answer:",answer);
}
return answer;
}
let str="352+*9-";
console.log(solution(str));
숫자에서 연산기호로 변경을 구현하지말고 stack에 계산한 값을 넣어주는 방법
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));