[코딩테스트/C++] 숫자 문자열과 영단어

Eu4ng·2023년 8월 12일
0

코딩테스트

목록 보기
1/1

제출 코드

프로그래머스 코딩테스트 연습 > 2021 카카오 채용연계형 인턴십 > 숫자 문자열과 영단어

#include <string>
#include <map>

using namespace std;

map<string, int> m;

int solution(string s) {
    string answer;
    
    // 맵 초기화
    m["zero"] = 0;
    m["one"] = 1;
    m["two"] = 2;
    m["three"] = 3;
    m["four"] = 4;
    m["five"] = 5;
    m["six"] = 6;
    m["seven"] = 7;
    m["eight"] = 8;
    m["nine"] = 9;

    // 버퍼
    string buffer;
    
    for(auto c : s)
    {
        // 숫자인지 확인
        if(isdigit(c))
            answer += c;
        else
            buffer += c;
        
        // 버퍼 문자열 확인
        if(m.find(buffer) != m.end())
        {
            answer += to_string(m[buffer]);
            buffer.clear();
        }
    }
    
    return stoi(answer);
}

배운점

string

  • int to string : string to_string(int c)
  • string to int : int stoi(string s)

char

  • char to int : char - '0'
  • int to char : int + '0'
  • 숫자인지 확인 : int isdigit(int c)
    • 숫자가 아니면 0 출력
    • 숫자인 경우 0이 아닌 값(4) 출력
profile
초보 개발자

0개의 댓글