[프로그래머스] 숨어있는 숫자의 덧셈 (2) - c++

삼식이·2025년 5월 5일

알고리즘

목록 보기
41/84

숨어있는 숫자의 덧셈 (2)

이 문제를 풀때 숫자면 tmp에 한 글자씩 더해 저장을 해놓고 알파벳을 마주칠 경우 해당 값을 int형으로 변환해서 answer변수에 누적합했다.

#include <string>
#include <vector>
#include <iostream>

using namespace std;

int solution(string my_string) {
    int answer = 0;
    string tmp = "";
    for(int i=0; i<my_string.size(); i++) {
        if (my_string[i] >= 'a' && my_string[i] <= 'z' ||
           my_string[i] >= 'A' && my_string[i] <= 'Z') {
            if(tmp!="") {
                answer += stoi(tmp);
                tmp = "";
            }
        } else {
            tmp += my_string[i];
        }
    }
    if (!tmp.empty()) {
        answer += stoi(tmp);
    }
    return answer;
}

다른 사람 풀이를 보니 훨씬 깔끔했다.
그리고 내가 자주 쓰지 않는 stringstream을 사용했기에 이에 대해 공부했다.

#include <string>
#include <vector>
#include <sstream>
#include <cctype>

using namespace std;

int solution(string my_string) {
    int answer = 0;
    // 숫자가 아닌 문자는 공백으로 바꿔서 숫자만 남기기
    for(auto& v : my_string) {
        if(!isdigit(v)) {
            v = ' ';
        }
    }

    stringstream ss(my_string);  // 문자열 스트림 초기화

    int tmp;
    // ss >> tmp가 성공적으로 값을 읽을 때만 루프 실행
    while (ss >> tmp) {
        answer += tmp;  // 읽은 숫자들을 더함
    }

    return answer;
}

먼저, isdigit()함수를 통해 숫자가 아닌 문자는 공백으로 바꾼다.

for(auto& v : my_string) {
        if(!isdigit(v)) {
            v = ' ';
        }
    }

해당 코드를 실행하면,
"a12b34c5" → " 12 34 5" 와 같이 숫자와 공백만이 남는다.

 stringstream ss(my_string);  // 문자열 스트림 초기화

stringstream은 문자열을 마치 cin처럼 다룰 수 있는 스트림이다.

stringstream을 이용하면 공백 단위로 숫자를 한 개씩 읽어올 수 있다

int tmp;
// ss >> tmp가 성공적으로 값을 읽을 때만 루프 실행
while (ss >> tmp) {
    answer += tmp;  // 읽은 숫자들을 더함
}

공백 기준으로 잘라낸 문자열 덩어리들 중 숫자인 것들을 int로 자동 형변환해서 tmp에 넣는다.

로직을 간단하게 구현할 수 있으므로, 앞으로는 다양한 C++의 함수와 기능들을 적극적으로 활용해봐야겠다.

0개의 댓글