-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution227.cs
50 lines (44 loc) · 1.19 KB
/
Solution227.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
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution227
{
/// <summary>
/// 227. Basic Calculator II - Medium
/// <a href="https://leetcode.com/problems/basic-calculator-ii">See the problem</a>
/// </summary>
public int Calculate(string s)
{
var stack = new Stack<int>();
var num = 0;
var sign = '+';
for (var i = 0; i < s.Length; i++)
{
if (char.IsDigit(s[i]))
{
num = num * 10 + s[i] - '0';
}
if ((!char.IsDigit(s[i]) && s[i] != ' ') || i == s.Length - 1)
{
if (sign == '+')
{
stack.Push(num);
}
else if (sign == '-')
{
stack.Push(-num);
}
else if (sign == '*')
{
stack.Push(stack.Pop() * num);
}
else if (sign == '/')
{
stack.Push(stack.Pop() / num);
}
sign = s[i];
num = 0;
}
}
return stack.Sum();
}
}