Expression Evaluate or ERR pos
JavaScript
Hard
3 views
Problem Description
One line expression has digits, + - * / ( ) and spaces. Evaluate with correct precedence. If any invalid character appears, print ERR pos (1-based index in original string).
Input Format
One line expression.
Output Format
One line result or ERR pos.
Constraints
Length up to 2e5.
Official Solution
const fs=require('fs');const expr=fs.readFileSync(0,'utf8');if(!expr.trim())process.exit(0);try{let s=expr;const tokens=[];for(let i=0;i<s.length;i++){const ch=s[i];if(ch===' '||ch==='\
'||ch==='\
'||ch==='\ ')continue;if(ch>='0'&&ch<='9'){let j=i;while(j<s.length && s[j]>='0'&&s[j]<='9')j++;tokens.push({t:'n',v:BigInt(s.slice(i,j))});i=j-1;continue;}if(ch==='+'||ch==='-'||ch==='*'||ch==='/'||ch==='('||ch===')'){tokens.push({t:'o',v:ch});continue;}throw {pos:i+1};}const out=[];const ops=[];const prec=o=>(o==='+'||o==='-')?1:2;for(let i=0;i<tokens.length;i++){const tok=tokens[i];if(tok.t==='n'){out.push(tok);continue;}const o=tok.v;if(o==='('){ops.push(o);continue;}if(o===')'){while(ops.length && ops[ops.length-1]!=='(')out.push({t:'o',v:ops.pop()});if(!ops.length)throw {pos:1};ops.pop();continue;}while(ops.length && ops[ops.length-1]!=='(' && prec(ops[ops.length-1])>=prec(o))out.push({t:'o',v:ops.pop()});ops.push(o);}while(ops.length){const o=ops.pop();if(o==='(')throw {pos:1};out.push({t:'o',v:o});}const st=[];for(const tok of out){if(tok.t==='n'){st.push(tok.v);continue;}const b=st.pop();const a=st.pop();if(a===undefined||b===undefined)throw {pos:1};let r=0n;if(tok.v==='+')r=a+b;else if(tok.v==='-')r=a-b;else if(tok.v==='*')r=a*b;else r=a/b;st.push(r);}if(st.length!==1)throw {pos:1};process.stdout.write(String(st[0]));}catch(e){process.stdout.write('ERR '+String(e.pos||1));}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!