-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy path0224-BasicCalculator.cs
58 lines (52 loc) · 1.53 KB
/
0224-BasicCalculator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//-----------------------------------------------------------------------------
// Runtime: 80ms
// Memory Usage: 24.2 MB
// Link: https://leetcode.com/submissions/detail/371999150/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
public class _0224_BasicCalculator
{
public int Calculate(string s)
{
var stack = new Stack<int>();
int num = 0;
var sign = 1;
var result = 0;
foreach (var ch in s)
{
if (char.IsDigit(ch))
num = 10 * num + (ch - '0');
else if (ch == '+')
{
result += sign * num;
sign = 1;
num = 0;
}
else if (ch == '-')
{
result += sign * num;
sign = -1;
num = 0;
}
else if (ch == '(')
{
stack.Push(result);
stack.Push(sign);
sign = 1;
num = 0;
result = 0;
}
else if (ch == ')')
{
result += sign * num;
num = result;
sign = stack.Pop();
result = stack.Pop();
}
}
return result + sign * num;
}
}
}