You're now a baseball game point recorder.
Given a list of strings, each string can be one of the 4 following types:
Integer (one round's score): Directly represents the number of points you get in this round.
"+" (one round's score): Represents that the points you get in this round are the sum of the last two valid round's points.
"D" (one round's score): Represents that the points you get in this round are the doubled data of the last valid round's points.
"C" (an operation, which isn't a round's score): Represents the last valid round's points you get were invalid and should be removed.
Each round's operation is permanent and could have an impact on the round before and the round after.
You need to return the sum of the points you could get in all the rounds.
Input: ["5","2","C","D","+"]
Output: 30
Explanation:
Round 1: You could get 5 points. The sum is: 5.
Round 2: You could get 2 points. The sum is: 7.
Operation 1: The round 2's data was invalid. The sum is: 5.
Round 3: You could get 10 points (the round 2's data has been removed). The sum is: 15.
Round 4: You could get 5 + 10 = 15 points. The sum is: 30.
我查找了错误消息的含义,其他人则指出我正在提供“错误信息”这一说法。但是,我个人找不到我的代码有什么问题。谁能帮我吗?这是目标:
a = 255;
bits = [1,2];
bitand(a,bitcmp(sum(2.^(bits-1)),'uint32'))
这是LeetCode问题,不是作业!
答案 0 :(得分:0)
std::stoi()
值不能转换为std::invalid_argument
,则 std::string
会引发int
异常。您没有捕获到该异常。如果它从main()
逃脱,则该应用程序将自行终止。
此外,您的循环是erase()
中来自ops
的元素,因此如果您不小心,则存在i
索引可能超出范围的风险,特别是因为没有执行任何范围检查。而且,在您无法正确管理ops
和i
的情况下,确实存在逻辑错误。
每当您需要一个循环来从要循环通过的容器中删除元素时,for
循环都是一个不好的选择。通常使用while
循环更好,这样您就可以更好地控制索引编制。
但是,您的整个代码通常是完全错误的,需要重新编写。您没有按照给定的指示进行操作,因为您没有按照指示计算每轮积分。您正在严格按照ops
中的输入值执行计算,这不是指令要求您执行的操作。
请尝试以下类似操作:
#include <string>
#include <vector>
#include <numeric>
#include <stdexcept>
class Solution {
public:
int calPoints(const std::vector<std::string> &ops)
{
std::vector<int> rounds;
int points;
for(auto &op : ops)
{
if (op == "C")
{
if (rounds.empty())
throw std::out_of_range("Not enough valid rounds!");
rounds.pop_back();
}
else if (op == "D")
{
if (rounds.empty())
throw std::out_of_range("Not enough valid rounds!");
points = rounds.back() * 2;
rounds.push_back(points);
}
else if (op == "+")
{
const std::vector<int>::size_type numRounds = rounds.size();
if (numRounds < 2)
throw std::out_of_range("Not enough valid rounds!");
points = rounds[numRounds-2] + rounds[numRounds-1];
rounds.push_back(points);
}
else
{
points = std::stoi(op);
rounds.push_back(points);
}
}
return std::accumulate(rounds.begin(), rounds.end(), 0);
}
};
这按预期从30
的输入中产生了["5","2","C","D","+"]
的总和。