본문 바로가기
알고리즘/프로그래머스

알고리즘(C++) / 프로그래머스 level 2 : 123 나라의 숫자

by clean_h 2021. 7. 28.
728x90

level 2 : 123 나라의 숫자

https://programmers.co.kr/learn/courses/30/lessons/12899?language=cpp 

 

코딩테스트 연습 - 124 나라의 숫자

 

programmers.co.kr

 

코드

//프로그래머스 124나라의 숫자
#include <iostream>
#include <string>
#include <vector>

using namespace std;

string solution(int n) {
    string answer = "";

    while (n) {
        n--;
        if (n % 3 == 0) {
            answer = "1" + answer;
        }
        else if (n % 3 == 1) {
            answer = "2" + answer;
        }
        else {
            answer = "4" + answer;
        }
        n /= 3;
    }

    return answer;
}

int main() {
    int n = 9;
    cout << solution(n) << "\n";
    return 0;
}

 

설명

0,1,2로 이루어진 3진법과 비슷하다. 

하지만 3진법은 0부터 시작 이 문제는 1부터 시작이다. 따라서 -1씩 해주도록한다. 

 

고찰

다른 사람의 풀이를 봤을 때 신기한 코드가 있었다.

"412"[0]; //string

다음과 같이 string을 사용할 수 있었다. 

"412"와 같은 string에서 배열처럼 index를 입력하여 출력해도 된다. 

string에서 배열같이 사용해도 된다는 것은 알았지만 다음과 같이 사용 가능한지는 처음 알게 되었다. 

728x90

댓글