Basic Calculator
Total Accepted: 29148 Total Submissions: 128464 Difficulty: Hard
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open(and closing parentheses), the Plus+or minus sign-,non-negativeIntegers and empty spaces.
Assume that the given expression was always valid.
Some Examples:
"1 + 1" = 2 "2-1 + 2" = 3 "(1+ (4+5+2)-3) + (6+8)" = 23
Note: don't use the eval built-in library function.
Subscribe to see which companies asked this question
Hide TagsStack MathHide Similar Problems(m) Evaluate Reverse Polish Notation (m) Basic Calculator II (m) Different Ways to Add parentheses (H) Expression ADD Operators
Java code:
public class Solution {public int calculate (String s) {stack<integer> Stack = new Stack<integ Er> (); int result = 0; int sign = 1; int n = s.length (); for (int i=0;i<n;i++) {char c = s.charat (i); if (Character.isdigit (c)) {int sum = c ' 0 '; while (I+1<n && character.isdigit (S.charat (i+1))) {sum = 10*sum + S.charat (i+1)-' 0 '; i++; } result + = sign * SUM; } else if (c== ' + ') {sign = 1; } else if (c== '-') {sign =-1; } else if (c== ' (') {Stack.push (result); Stack.push (sign); sign = 1; result = 0; } else if (c== ') ') {result = result * Stack.pop () + Stack.pop (); }} return result; }}
Leetcode:basic Calculator