# Basic Calculator

224. Basic Calculator

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-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

``````"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23
``````

Note: Do not use the eval built-in library function.

``````class Solution {
func calculate(_ s: String) -> Int {
if s.count == 0 {
return 0
}

var stack: [Int] = []
var sign = 1
var result = 0

var i = 0
while i < s.count {
let c = s[s.index(s.startIndex, offsetBy: i)]

if isDigit(c) {
var num = Int(String(c))!

while i < s.count - 1
&& isDigit(s[s.index(s.startIndex, offsetBy: i + 1)]) {
num = num * 10
+ Int(String(s[s.index(s.startIndex, offsetBy: i + 1)]))!
i += 1
}

result += num * sign
} else if c == "+" {
sign = 1
} else if c == "-" {
sign = -1
} else if c == "(" {
stack.append(result)
stack.append(sign)
result = 0
sign = 1
} else if c == ")" {
result = result * stack.removeLast() + stack.removeLast()
}

i += 1
}

return result
}

func isDigit(_ c: Character) -> Bool {
if let val = Int(String(c)) {
if val >= 0 && val <= 9 {
return true
}
}

return false
}
}
``````
``````public class Solution {
public int calculate(String s) {
if (s == null || s.length() == 0) {
return 0;
}

int result = 0;
int sign = 1;
Stack<Integer> stack = new Stack<>();

for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);

if (Character.isDigit(c)) {
int sum = c - '0';

while (i < s.length() - 1 && Character.isDigit(s.charAt(i + 1))) {
sum = 10 * sum + s.charAt(i + 1) - '0';
i++;
}

result += sum * sign;
} else if (c == '+') {
sign = 1;
} else if (c == '-') {
sign = -1;
} else if (c == '(') {
stack.push(result);
stack.push(sign);
result = 0;
sign = 1;
} else if (c == ')') {
result = result * stack.pop() + stack.pop();
}
}

return result;
}
}
``````

Hope this helps,
Michael