One Pager Cheat Sheet
- Let's
programa very basiccalculator, handlingpositive,negativesymbols,parentheses, andspaces, without usingeval function! - In most languages, you can evaluate code strings
quickly and easilyusingeval. - We can
break downthe problem into parsing and evaluatingsymbolssuch asintegers,signs/operations,parenthesisandspaces, anditerate throughan expression string totransform itinto a form understandable by the machine, withsome caveatsin the processing order. - Adding a negative number to our running result is the key to solving the problem of subtraction.
- We can
keep trackof our sign while converting the signs of numbers by using1or-1to represent the+or-operations respectively. - Leveraging two
stacksto keep track of theresultandoperationswithin the parentheses is the key to solving this challenging problem. - We
skipthatiterationif thecurrentcharacter is aspace. - We can iterate through the input of length
ninO(n)time and space complexity. - We can extend our previous solution to handle Multiplication and Division by using a
stackto store multipliers and dividers and multiplying or dividing the result of eachfor loopiteration by this stack as it pops values off. Byrecreatingthe parentheses expression on a stack, we can still use the left-to-right approach to parse"4*(3+2)", instead of being "drawn to the parentheses".
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx55
}var assert = require('assert');​function calculator(str) { let result = 0, sign = 1; const stack = [], operationStack = [];​ for (let i = 0; i < str.length; i++) { const curr = str.charAt(i); if (curr === ' ') { continue; } else if (curr === '+') { sign = 1; } else if (curr === '-') { sign = -1; } else if (curr >= '0' && curr <= '9') { let num = curr; while ( i + 1 < str.length && str.charAt(i + 1) >= '0' && str.charAt(i + 1) <= '9' ) { num += str.charAt(i + 1); i++; } result += sign * parseInt(num); } else if (curr === '(') { stack.push(result); result = 0; operationStack.push(sign); sign = 1;OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Great job getting through this. Let's move on.
If you had any problems with this tutorial, check out the main forum thread here.


