알고리즘/프로그래머스
[C++] (공백분리) 컨트롤 제트
parkkingcar
2023. 5. 19. 13:34
컨트롤 제트
숫자와 "Z"가 공백으로 구분되어 담긴 문자열이 주어집니다. 문자열에 있는 숫자를 차례대로 더하려고 합니다. 이 때 "Z"가 나오면 바로 전에 더했던 숫자를 뺀다는 뜻입니다. 숫자와 "Z"로 이루어진 문자열 s가 주어질 때 답을 return
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int solution(string s) {
int answer = 0;
int tmp;
stringstream ss(s);
vector<string> words;
string word;
while (getline(ss, word, ' ')) {
words.push_back(word);
}
for (int i = 0; i < words.size(); i++) {
if (words[i] == "Z") {
answer -= tmp;
} else {
answer += stoi(words[i]);
tmp = stoi(words[i]);
}
}
return answer;
}
공백 기준으로 문자열분리
[C++] String 공백 분리
C++ STL sstream을 사용하여 문자열의 공백을 기준으로 분리합니다. 공백을 기준으로 분리한 후 변수에 저장, vector에 저장 #include #include #include #include using namespace std; int main(){ // 공백 분리할 문자열
parkkingcar.tistory.com