Mini Calculator (No eval)
JavaScript
Medium
2 views
Problem Description
Given an expression with + - * / and non-negative integers, compute the result using correct precedence (* and / first). Integer division should floor.
Input Format
One line expression, may have spaces.
Output Format
One integer result.
Sample Test Case
Input:
10 + 2 * 3 - 4 / 2
Constraints
Expression is valid, numbers fit in 64-bit.
Official Solution
const fs=require('fs');let s=fs.readFileSync(0,'utf8').trim();if(!s)process.exit(0);s=s.replace(/\\s+/g,'');let nums=[];let ops=[];const prec=o=>(o==='+'||o==='-')?1:2;const apply=()=>{const b=nums.pop();const a=nums.pop();const o=ops.pop();let r=0n;const A=BigInt(a),B=BigInt(b);if(o==='+')r=A+B;else if(o==='-')r=A-B;else if(o==='*')r=A*B;else r=A/B;nums.push(r);};let i=0;while(i<s.length){let j=i;while(j<s.length && /\\d/.test(s[j]))j++;const n=s.slice(i,j);nums.push(BigInt(n));i=j;if(i>=s.length)break;const o=s[i++];while(ops.length && prec(ops[ops.length-1])>=prec(o))apply();ops.push(o);}while(ops.length)apply();process.stdout.write(String(nums[0]));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!