[백준] 1541 잃어버린 괄호
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
string input;
cin >> input;
int answer = 0;
string tempStr = "";
int temp = 0;
bool minus = false;
int len = input.length();
for (int i = 0; i < len; ++i) {
if (input[i] == '-') {
temp += stoi(tempStr);
tempStr = "";
if (!minus) {
answer += temp;
temp = 0;
}
else {
answer -= temp;
temp = 0;
}
minus = true;
continue;
}
if (input[i] == '+') {
temp += stoi(tempStr);
tempStr = "";
continue;
}
tempStr += input[i];
}
if (tempStr != "") {
temp += stoi(tempStr);
tempStr = "";
if (!minus) {
answer += temp;
}
else {
answer -= temp;
}
}
cout << answer;
return 0;
}
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
string input;
cin >> input;
vector<int> inputVec;
string tempStr = "";
int len = input.length();
for (int i = 0; i < len; ++i) {
if (input[i] == '-') {
inputVec.push_back(stoi(tempStr));
tempStr = "";
inputVec.push_back(-2);
continue;
}
if (input[i] == '+') {
inputVec.push_back(stoi(tempStr));
tempStr = "";
inputVec.push_back(-1);
continue;
}
tempStr += input[i];
}
if (tempStr != "") {
inputVec.push_back(stoi(tempStr));
}
bool minus = false;
int answer = 0;
int temp = 0;
for (int i = 0; i < inputVec.size(); ++i) {
if (inputVec[i] == -1) {
continue;
}
if (inputVec[i] == -2) {
if (!minus) {
answer += temp;
temp = 0;
minus = true;
}
else {
answer -= temp;
temp = 0;
}
continue;
}
temp += inputVec[i];
}
if (temp != 0) {
if (!minus) {
answer += temp;
}
else {
answer -= temp;
}
}
cout << answer;
return 0;
}