File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
Stack/224.Basic-Calculator Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ int calculate (string s)
4+ {
5+ stack<int >nums;
6+ stack<int >sign;
7+ s.insert (s.begin (),' +' );
8+
9+ int curResult=0 ;
10+ for (int i=0 ; i<s.size (); i++)
11+ {
12+ if (s[i]==' (' )
13+ {
14+ nums.push (curResult);
15+ curResult=0 ;
16+ sign.push (1 );
17+ }
18+ else if (s[i]==' )' )
19+ {
20+ curResult*=sign.top ();
21+ sign.pop ();
22+ curResult+=nums.top ();
23+ nums.pop ();
24+ }
25+ else if (s[i]==' +' )
26+ sign.push (1 );
27+ else if (s[i]==' -' )
28+ sign.push (-1 );
29+ else if (s[i]>=' 0' && s[i]<=' 9' )
30+ {
31+ int i0=i;
32+ while (i<s.size () && s[i]>=' 0' && s[i]<=' 9' )
33+ i++;
34+ int num = stoi (s.substr (i0,i-i0));
35+ curResult+=sign.top ()*num;
36+ sign.pop ();
37+ i--;
38+ }
39+ }
40+
41+ return curResult;
42+
43+ }
44+ };
You can’t perform that action at this time.
0 commit comments