Postfix Calculator
JavaScript
Medium
6 views
Problem Description
Given a postfix expression with space-separated tokens (numbers and + - * /). Evaluate it and print result. Division is integer division toward zero.
Input Format
One line postfix expression.
Output Format
One integer.
Constraints
Tokens count up to 2e5.
Official Solution
const fs=require('fs');const t=fs.readFileSync(0,'utf8').trim();if(!t)process.exit(0);const a=t.split(/\\s+/);let st=[];for(const tok of a){if(tok==='+'||tok==='-'||tok==='*'||tok==='/'){const b=BigInt(st.pop());const c=BigInt(st.pop());let r=0n;if(tok==='+')r=c+b;else if(tok==='-')r=c-b;else if(tok==='*')r=c*b;else r=c/b;st.push(r.toString());}else st.push(tok);}process.stdout.write(st.length?String(st[0]):'0');
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!