2011. Final Value of Variable After Performing Operations
Description :
There is a programming language with only four operations and one variable X:
- ++X and X++ increments the value of the variable X by 1.
- –X and X-- decrements the value of the variable X by 1.
Initially, the value of X is 0.
Given an array of strings operations containing a list of operations, return the final value of X after performing all the operations.
Example 1:
Input: operations = [“–X”,“X++”,“X++”]
Output: 1
Explanation: The operations are performed as follows:
Initially, X = 0.
–X: X is decremented by 1, X = 0 - 1 = -1.
X++: X is incremented by 1, X = -1 + 1 = 0.
X++: X is incremented by 1, X = 0 + 1 = 1.
Example 2:
Input: operations = [“++X”,“++X”,“X++”]
Output: 3
Explanation: The operations are performed as follows:
Initially, X = 0.
++X: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
X++: X is incremented by 1, X = 2 + 1 = 3.
Example 3:
Input: operations = [“X++”,“++X”,“–X”,“X–”]
Output: 0
Explanation: The operations are performed as follows:
Initially, X = 0.
X++: X is incremented by 1, X = 0 + 1 = 1.
++X: X is incremented by 1, X = 1 + 1 = 2.
–X: X is decremented by 1, X = 2 - 1 = 1.
X–: X is decremented by 1, X = 1 - 1 = 0.
Constraints:
- 1 <= operations.length <= 100
- operations[i] will be either “++X”, “X++”, “–X”, or “X–”.
Hint1
There are only two operations to keep track of.
Hint2
Use a variable to store the value after each operation.
solution1
class Solution {
public:
int finalValueAfterOperations(vector<string>& operations) {
int x =0;
for(auto &i:operations){
if (i=="X++" || i=="++X")
x+=1;
else
x-=1;
}
return x;
}
};
insert用法
#include <iostream>
#include <vector>
#include <array>
using namespace std;
int main()
{
std::vector<int> demo{1,2};
//第一种格式用法
demo.insert(demo.begin() + 1, 3);//{1,3,2}
//第二种格式用法
demo.insert(demo.end(), 2, 5);//{1,3,2,5,5}
//第三种格式用法
std::array<int,3>test{ 7,8,9 };
demo.insert(demo.end(), test.begin(), test.end());//{1,3,2,5,5,7,8,9}
//第四种格式用法
demo.insert(demo.end(), { 10,11 });//{1,3,2,5,5,7,8,9,10,11}
for (int i = 0; i < demo.size(); i++) {
cout << demo[i] << " ";
}
return 0;
}
emplace()用法
emplace() 每次只能插入一个元素,而不是多个。
该函数的语法格式如下:
iterator emplace (const_iterator pos, args…);
其中,pos 为指定插入位置的迭代器;args… 表示与新插入元素的构造函数相对应的多个参数;该函数会返回表示新插入元素位置的迭代器。
简单的理解 args…,即被插入元素的构造函数需要多少个参数,那么在 emplace() 的第一个参数的后面,就需要传入相应数量的参数。
举个例子:
#include <vector>
#include <iostream>
using namespace std;
int main()
{
std::vector<int> demo1{1,2};
//emplace() 每次只能插入一个 int 类型元素
demo1.emplace(demo1.begin(), 3);
for (int i = 0; i < demo1.size(); i++) {
cout << demo1[i] << " ";
}
return 0;
}