Created
June 21, 2018 21:09
-
-
Save pinkmomo027/bcac1e9a664b2dcbb68b11b0888d86a9 to your computer and use it in GitHub Desktop.
only + - ( )
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| } |
Author
pinkmomo027
commented
Jun 21, 2018
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