/* *****************************************************************************
* %{QMAKE_PROJECT_NAME}
* Copyright (c) %YEAR% killerbee
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
* ****************************************************************************/
#include
#include
#include
#include
using std::string;
using std::vector;
bool is_number(const std::string& op);
class Solution {
public:
int calPoints(vector& ops) {
std::vector nums;
for (std::size_t i{}; i < ops.size(); ++i) {
if (is_number(ops[i])) {
// record a new score
nums.push_back(std::stoi(ops[i]));
} else {
if (ops[i] == "+") {
// record a new score that is the sum of the previous two scores
// it is guaranteed there will always be two previous scores
nums.push_back(nums[nums.size() - 1] + nums[nums.size() - 2]);
} else if (ops[i] == "D") {
// record a new score that is double the previous score
// it is guaranteed there will always be a previous score
nums.push_back(nums.back() * 2);
} else if (ops[i] == "C") {
// invalidate the previous score, removing it from the record
// it is guaranteed there will always be a previous score
nums.pop_back();
}
}
}
return std::accumulate(nums.begin(), nums.end(), 0);
}
};
bool is_number(const std::string& op) {
// first check if number starts with a sign character
std::size_t i = 0;
if (op[0] == '-' || op[0] == '+') {
i = 1;
}
for (; i < op.length(); ++i) {
if (! std::isdigit(op[i])) {
return false;
}
}
return true;
}