classSolution { /* Contains -1's */ intgetsign(vector<int>& v){ int sign = 1; for (int e: v) { sign *= e; } return sign; } intgetnum(string s, int& i){ string n; while (i < s.size() && isdigit(s[i])) { n+=s[i]; i++; } return stoi(n); } public: intcalculate(string s){ vector<int> signs; for (int i = 0; i < s.size(); i++) { if (isdigit(s[i])) { num = getnum(s, i) sum += sign * num; } elseif (s[i] == '(') { // when we start a new group // we calculate the new sign to // apply // first push the last sign we e signs.push_back(sign); sign = getsign(signs);
// skip over any extra '('? //while (i < s.size() && s[i] == '(') i++;
} elseif (s[i] == ')') { // we need to pop the signs stack signs.pop_back(); // todo skip over extra ')'? } elseif (s[i] == '-') { sign = -1; } elseif (s[i] == '+') { sign = 1; } } } };
classSolution { /* Contains -1's */ intgetsign(vector<int>& v){ int sign = 1; for (int e: v) { sign *= e; } return sign; } intgetnum(string s, int& i){ string n; while (i < s.size() && isdigit(s[i])) { n+=s[i]; i++; } return stoi(n); } public: intcalculate(string s){ vector<int> signs = {1}; int sum = 0; int num = 0; int sign = 1; for (int i = 0; i < s.size(); i++) { if (isdigit(s[i])) { num = getnum(s, i); sum += sign * num; cout << "d = " << sign * num << endl; } elseif (s[i] == '(') { // when we start a new group // we calculate the new sign to // apply // first push the last sign we e signs.push_back(sign); //sign = getsign(signs);
// skip over any extra '('? //while (i < s.size() && s[i] == '(') i++;
} elseif (s[i] == ')') { // we need to pop the signs stack signs.pop_back(); // todo skip over extra ')'? } elseif (s[i] == '-') { sign = signs.back() * -1; } elseif (s[i] == '+') { sign = signs.back(); } } return sum; } };