leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0224.cpp (738B)


      1 class Solution {
      2   public:
      3     int calculate(const string &s) const {
      4         int res = 0;
      5         vector<int> signs(2, 1);
      6         for (int i = 0; i < s.size(); i++) {
      7             if (s[i] >= '0') {
      8                 int number = 0;
      9                 while (i < s.size() && isdigit(s[i])) {
     10                     number = 10 * number + (s[i++] - '0');
     11                 }
     12                 res += signs.back() * number;
     13                 signs.pop_back();
     14                 i--;
     15             } else if (s[i] == '(' && s[i + 1] == '-') {
     16             } else if (s[i] == ')')
     17                 signs.pop_back();
     18             else if (s[i] != ' ')
     19                 signs.push_back(signs.back() * (s[i] == '-' ? -1 : 1));
     20         }
     21         return res;
     22     }
     23 };