One Pager Cheat Sheet
- Let's
program
a very basiccalculator
, handlingpositive
,negative
symbols,parentheses
, andspaces
, without usingeval function
! - In most languages, you can evaluate code strings
quickly and easily
usingeval
. - We can
break down
the problem into parsing and evaluatingsymbols
such asintegers
,signs/operations
,parenthesis
andspaces
, anditerate through
an expression string totransform it
into a form understandable by the machine, withsome caveats
in the processing order. - Adding a negative number to our running result is the key to solving the problem of subtraction.
- We can
keep track
of our sign while converting the signs of numbers by using1
or-1
to represent the+
or-
operations respectively. - Leveraging two
stacks
to keep track of theresult
andoperations
within the parentheses is the key to solving this challenging problem. - We
skip
thatiteration
if thecurrent
character is aspace
. - We can iterate through the input of length
n
inO(n)
time and space complexity. - We can extend our previous solution to handle Multiplication and Division by using a
stack
to store multipliers and dividers and multiplying or dividing the result of eachfor loop
iteration by this stack as it pops values off. By
recreatingthe 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.
xxxxxxxxxx
55
}
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.