[C++] 문자열 다루기 기본 - isDigit()

wansuper·2023년 12월 27일
0

CodingTest

목록 보기
15/34

GPT 풀이

#include <string.h>
#include <vector>
#include <iostream>

using namespace std;

bool solution(string s) {
    bool answer = true;
    
    if (s.size() != 4 && s.size() != 6) {
        answer = false;
    } else {

        for (char c : s) {
            if (!isdigit(c)) {
                answer = false;
                break;
            }
        }
    }
    
    return answer;
}

int isDigit(int i)

  • C++ 헤더 파일: (프로그래머스에서 이거 선언 안했는데 됐다..?)
  • 사용법 및 설명: 매개변수로 들어온 char 타입이 10진수 숫자로 변경이 가능하면 0이 아닌 숫자(true), 아니면 0(false)를 반환하는 함수
  • 함수 원형을 살펴보면 매개변수 타입이 char 타입이 아닌 int 타입으로 받는걸 볼 수 있는데, 이는 char 타입이 아스키 코드 번호로 들어갈 수 있기 때문임.
  • 아스키 코드표에서 48~57번에 매칭되는 문자 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'가 들어오면 True를 반환하는 형태

틀린 내 풀이

#include <string.h>
#include <vector>
#include <iostream>

using namespace std;

bool solution(string s) {
    bool answer = true;
    
    for (int i = 0; i < s.size(); i++) {
       
        if ((int)s[i] > 57) {
            answer = false;
            cout << (int)s[i] << " ";
            break;
        } else {
            answer = true;
            cout << (int)s[i] << " ";
        }
    }
    return answer;
}

- 패착요인:

  • 당연히 문자열의 길이가 4 or 6으로 들어오겠구나 하고 예외처리를 해두지 않았음.
  • 위의 for문을 다음 코드의 else 문 내부에 넣어두니 정확도 84.7% -> 100%로 만족할 수 있었다.
if (s.size() != 4 && s.size() != 6) {
        answer = false;
    } else { ... }
  • 결론: 문제를 잘 읽고 사소한 부분도 완벽하게 검토하자.
profile
🚗 Autonomous Vehicle 🖥️ Study Alone

0개의 댓글