N Log

프로그래머스 입문 120894 영어가 싫어요

문제

출처

소문자로 표기된 영어 숫자가 공백 없는 문자열로 주어진다.
이를 정수로 변환해 반환하시오.

numbers result
“onetwothreefourfivesixseveneightnine” 123456789
“onefourzerosixseven” 14067

풀이

첫 글자 분기로 숫자 영단어 읽기

long long solution(const char* numbers)
{
    const char* ptr = numbers;
    long long result = 0;

    while (*ptr != '\0')
    {
        if (*ptr == 'z')  // zero
        {
            result = result * 10 + 0;
            ptr += 4;
        }
        else if (*ptr == 'o')  // one
        {
            result = result * 10 + 1;
            ptr += 3;
        }
        else if (*ptr == 't' && *(ptr + 1) == 'w')  // two
        {
            result = result * 10 + 2;
            ptr += 3;
        }
        else if (*ptr == 't' && *(ptr + 1) == 'h')  // three
        {
            result = result * 10 + 3;
            ptr += 5;
        }
        else if (*ptr == 'f' && *(ptr + 1) == 'o')  // four
        {
            result = result * 10 + 4;
            ptr += 4;
        }
        else if (*ptr == 'f' && *(ptr + 1) == 'i')  // five
        {
            result = result * 10 + 5;
            ptr += 4;
        }
        else if (*ptr == 's' && *(ptr + 1) == 'i')  // six
        {
            result = result * 10 + 6;
            ptr += 3;
        }
        else if (*ptr == 's' && *(ptr + 1) == 'e')  // seven
        {
            result = result * 10 + 7;
            ptr += 5;
        }
        else if (*ptr == 'e')  // eight
        {
            result = result * 10 + 8;
            ptr += 5;
        }
        else if (*ptr == 'n')  // nine
        {
            result = result * 10 + 9;
            ptr += 4;
        }
    }

    return result;
}

현재 위치의 첫 글자와 필요한 경우 다음 글자를 확인해 어떤 숫자 영단어인지 판별한다.
숫자를 찾을 때마다 결과에 한 자리씩 붙이고, 해당 단어의 길이만큼 포인터를 이동한다.

Lookup table과 문자열 비교로 숫자 변환하기

#include <string.h>

long long solution(const char* numbers)
{
    const char* words[] = {
        "zero", "one", "two", "three", "four",
        "five", "six", "seven", "eight", "nine"
    };
    int word_lengths[] = { 4, 3, 3, 5, 4, 4, 3, 5, 5, 4 };

    long long result = 0;
    const char* ptr = numbers;

    while (*ptr != '\0')
    {
        for (int digit = 0; digit < 10; digit++)
        {
            if (strncmp(ptr, words[digit], word_lengths[digit]) == 0)
            {
                result = result * 10 + digit;
                ptr += word_lengths[digit];
                break;
            }
        }
    }

    return result;
}

숫자 영단어와 각 영단어의 길이를 배열에 미리 저장해 둔다.
현재 위치 ptr에서 각 숫자 영단어의 길이만큼 strncmp로 비교해 일치하는 단어를 찾는다.
일치하는 영단어를 찾으면 그 인덱스를 숫자로 사용하고, 미리 저장한 길이만큼 포인터를 이동한다.