[프로그래머스/C++]Lv.0 - 숨어있는 숫자의 덧셈 (2)

YH J·2023년 4월 18일
0

프로그래머스

목록 보기
35/168

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/120864

내 풀이

isdigit (해당 char가 숫자면 true) 연속되는 숫자는 하나의 숫자로 간주하므로 숫자가 연속되면 기존에 추가된 숫자에 10을 곱해서 올리고 1의자리를 추가하다가 영어를 만나면 answer에 넣어줌.

내 코드

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

using namespace std;

int solution(string my_string) {
    int answer = 0;
    int n = 0;
    
    for(int i = 0; i < my_string.length(); i++)
    {
        if(isdigit(my_string[i]))
            n = n * 10 + my_string[i] - '0';
        else
        {
            answer += n;
            n = 0;
        }
    }
    answer += n;
    return answer;
}

다른 사람의 풀이

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

using namespace std;

int solution(string my_string) {
    int answer = 0;
    for(auto& v : my_string)
    {
        if(!isdigit(v))
        {
            v = ' ';
        }
    }

    stringstream ss;
    ss.str(my_string);

    int tmp = 0;
    while(ss)
    {
        answer += tmp;
        ss >> tmp;
    }

    return answer;
}

다른 사람의 풀이 해석

string 내의 모든 영어를 공백으로 변환한뒤 stringstream 사용해서 숫자들 다 뽑아서 더해줌

profile
게임 개발자 지망생

0개의 댓글