In the above example, we simply converted the signage when we encountered a minus symbol-- so we need to keep some concept of what sign
we're at. This will allow us to keep track of what operation we're performing, whether it's +
or -
.
Assuming we handle signage with a 1
or a -1
, our method so far starts to look something like this:
xxxxxxxxxx
20
function calculator(str) {
let result = 0, sign = 1;
for (let i = 0; i < str.length; i++) {
const curr = str.charAt(i);
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);
}
}
return result;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment