Skip to content

Instantly share code, notes, and snippets.

@pinkmomo027
Created June 21, 2018 21:09
Show Gist options
  • Save pinkmomo027/bcac1e9a664b2dcbb68b11b0888d86a9 to your computer and use it in GitHub Desktop.
Save pinkmomo027/bcac1e9a664b2dcbb68b11b0888d86a9 to your computer and use it in GitHub Desktop.
only + - ( )
function basicCalc(str) {
let result = 0, length = str.length, sign = 1, char;
let stack = [];
for (let i = 0; i < length; i++) {
char = str.charAt(i);
if (char >= '0') {
//find all the chars
let num = 0;
while(i < length && str[i] >= '0') {
num = num * 10 + parseInt(str[i++]);
}
i--;
result = result + sign * num;
} else if (char == '+') {
sign = 1;
} else if (char == '-') {
sign = -1;
} else if (char == '(') {
stack.push(result);
stack.push(sign);
result = 0;
sign = 1;
} else if (char == ')') {
let stackSign = stack.pop();
let stackResult = stack.pop();
result = stackResult + result * stackSign;
}
}
console.log("Result = ", result);
return result;
}
@pinkmomo027
Copy link
Author

basicCalc("1 + 12");
basicCalc(" 2-1 + 2 ");
basicCalc("(1+(4+5+2)-3)-(62+8)");

@pinkmomo027
Copy link
Author

Result =  13
Result =  3
Result =  -61
[Finished in 0.1s]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment