Last active
July 14, 2022 22:25
-
-
Save DragonOsman/106bcd3926cdf895949f70185d49f9c9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bool is_number(const std::string& op); | |
class Solution { | |
public: | |
int calPoints(vector<string>& ops) { | |
std::vector<int> 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 | |
int sum{nums[nums.size() - 1] + nums[nums.size() - 2]}; | |
nums.push_back(sum); | |
} | |
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 | |
int doubled{nums[nums.size() - 1] * 2}; | |
nums.push_back(doubled); | |
} | |
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 | |
char sign = ' '; | |
bool flag = false; // to check for digits | |
if (op[0] == '-' || op[0] == '+') | |
{ | |
sign = op[0]; | |
for (std::size_t i{1}; i < op.length(); ++i) | |
{ | |
if (std::isdigit(op[i])) | |
{ | |
flag = true; | |
} | |
else | |
{ | |
flag = false; | |
} | |
} | |
} | |
else | |
{ | |
for (std::size_t i{}; i < op.length(); ++i) | |
{ | |
if (std::isdigit(op[i])) | |
{ | |
flag = true; | |
} | |
else | |
{ | |
flag = false; | |
} | |
} | |
} | |
return flag; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment