백준 - 5622번 다이얼(문자열, getchar())

Kiwoong Park·2023년 5월 13일
0

문제


C++ 풀이

문제에 주어진대로 26개의 알파벳에 해당하는 숫자를 배열로 만들어주면 아래와 같은 코드로 만들 수 있다. Range-based for loop 를 사용하여 순회하면서 tot 값에 더해가면 된다.

#include <iostream>
using namespace std;
int main(){
    int tot=0,dial[26]={2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9};
    string str;
    cin >> str;
    for (char c:str) {
        tot+=dial[int(c)-'A']+1;
    }
    cout << tot;
}

숏코딩 분석하기

실제 시간복잡도는 이중 루프로 인해 올라가지만 메모리 사용이 줄어드는 코드라고 할 수 있다.

#import<ios>
int c,s;
main(){
    while((c=getchar())-10)
        for(int a:"  CFILOSV")
            s+=c>a;
    printf("%d",s);
}

-10 은 '\n' 개행문자를 의미한다. 즉 입력이 끝날 때까지
getchar()함수를 통해 읽어드린 문자 값을 int값으로 리턴하여 정수변수 c에 저장한다.

while문 안의 range-based for문을 통해 (int a:" CFILOSV")를 순회하는데 whitespace(blankspace)의 경우 아스키코드 32이며, 중요한 포인트는 "abc"이렇게 3개의 문자여도 for문을 도는 횟수는 '\0'까지 포함하여 4번을 순회한다!

In C++, when you write a range-based for loop like for (a : "abc") {...}, it includes the terminating null character '\0'. So, the loop will iterate 4 times: once for each character 'a', 'b', 'c', and the terminating null character '\0'.

Therefore, when using a range-based for loop over a string literal in C++, you need to be aware that it includes the terminating null character, and the loop will iterate one additional time to account for it.

A,B,C 중 하나가 들어오면 숫자 2 다이얼로 총 3번을 움직여야 하므로 앞의 공백 2개 + null 보다 커서 3번을 더하고, 이런식으로 D,E,F가 들어오면 1번 더 더하는 식으로 로직이 구현되어 있다!

profile
You matter, never give up

0개의 댓글