본문 바로가기

Study/Algorithm

[Level 2] 1. 124 나라의 숫자

1. 124 나라의 숫자


Algorithm - Level 2


- 풀이


3진법으로 보면 0 = 4, 1 = 1, 2 = 2가 되므로, 해당 수를 3진법으로 생각하여 계산하는 것이 편리.


각 자리에 + 3, + 6, + 9를 하면서 증가하는데 이 때 3을 나눈 수가 다음 자리의 수가 된다.


재귀함수를 이용하여 풀이.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <string>
#include <vector>
#include <iostream>
 
using namespace std;
 
string translation(string s, int n){
    int count = (n-1/ 3;
    int tmp = n - (count * 3);
    
    if(count >= 1)
        s = translation(s, count);
    if(tmp == 3)
        s.push_back('4');
    else
        s.push_back(tmp+0x30);
 
    return s;
}
 
string solution(int n) {
    string answer = "";
    
    answer = translation(answer, n);
 
    return answer;
}
 
int main(void){
    int n = 19;
    for(int i=1; i<20; i++){
        string s = solution(i);
        cout << s << endl;
    }
}
cs


++++++++++++++++++++++++++++++++++++++++++


어떤 분이 푼 것을 보았는데 "412"[a] 라는 식을 통해 해결하였다.

???

'Study > Algorithm' 카테고리의 다른 글

[Level 2] 6. 숫자의 표현  (0) 2018.07.23
[Level 2] 5. 땅따먹기  (0) 2018.07.20
[Level 2] 4. 다음 큰 숫자  (0) 2018.07.20
[Level 2] 3. 올바른 괄호  (0) 2018.07.18
[Level 2] 2. 가장 큰 정사각형 찾기  (0) 2018.07.18