https://school.programmers.co.kr/learn/courses/30/lessons/120853
한글자 한글자 하면서 숫자인지 공백인지 -인지 다 검사해서 계산했다. stringstream을 모를때라 이렇게 하였다.
#include <string>
#include <vector>
#include <cctype>
using namespace std;
int solution(string s) {
int answer = 0;
int b = 0;
int c = 0;
bool m = false;
for(const auto& a : s)
{
if(isdigit(a))
{
b = b * 10 + a - '0';
}
else if(a == '-')
{
m = true;
}
else if(a == 'Z')
{
answer -= c;
b = 0;
}
else if(a == ' ')
{
if(m)
{
answer -= b;
c = b * (-1);
}
else
{
answer += b;
c = b;
}
m = false;
b = 0;
}
}
if(m)
answer -= b;
else
answer += b;
return answer;
}
#include <string>
#include <vector>
#include <stack>
#include <sstream>
using namespace std;
int solution(string s) {
int answer = 0;
stringstream ss;
ss.str(s);
stack<int> st;
int t = 0;
string tmp = "0";
while(ss>>tmp)
{
if(tmp == "Z")
{
st.pop();
}
else
{
t = stoi(tmp);
st.push(t);
}
}
while(!st.empty())
{
answer += st.top();
st.pop();
}
return answer;
}
stringstream을 사용하여 파싱하면서 stack에 숫자들을 넣는데 Z를만나면 최근에 넣은걸 pop시킨다. 굳이 빼는 연산 없이 그냥 pop해버리면 된다. 파싱이 끝나면 채워진 스택으로 합을 계산한다.