File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
Stack/227.Basic-Calculator-II Expand file tree Collapse file tree 1 file changed +51
-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+ string S = " +" ;
6+ for (auto ch:s)
7+ {
8+ if (ch==' ' ) continue ;
9+ S.push_back (ch);
10+ if (ch==' (' )
11+ S+=" +" ;
12+ }
13+ s = S;
14+
15+ vector<int >nums;
16+ vector<int >signs;
17+ int sign;
18+
19+ for (int i=0 ; i<S.size (); i++)
20+ {
21+ if (s[i]==' +' || s[i]==' -' )
22+ {
23+ signs.push_back (s[i]==' +' ?1 :-1 );
24+ }
25+ else if (s[i]==' *' || s[i]==' /' )
26+ {
27+ int j = i+1 ;
28+ while (j<s.size () && isdigit (s[j]))
29+ j++;
30+ int num = stoi (s.substr (i+1 ,j-i-1 ));
31+ if (s[i]==' *' ) nums.back () *= num;
32+ else if (s[i]==' /' ) nums.back () /= num;
33+ i = j-1 ;
34+ }
35+ else if (isdigit (s[i]))
36+ {
37+ int j = i;
38+ while (j<s.size () && isdigit (s[j]))
39+ j++;
40+ int num = stoi (s.substr (i,j-i));
41+ nums.push_back (num);
42+ i = j-1 ;
43+ }
44+ }
45+
46+ int ret = 0 ;
47+ for (int i=0 ; i<nums.size (); i++)
48+ ret+=nums[i]*signs[i];
49+ return ret;
50+ }
51+ };
You can’t perform that action at this time.
0 commit comments