Post

[월간 코드 챌린지 시즌1] 3진법 뒤집기 (C++)

https://school.programmers.co.kr/learn/courses/30/lessons/68935

풀이

2진법을 구하는 식에 3을 대입해 풀어줬다.

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <string>
#include <vector>
#include <cmath>

using namespace std;

int solution(int n) {
    string trit = "";
    while(n > 0)
        trit += to_string(n % 3),    n /= 3;
    
    int answer = 0;
    for(int i = trit.length() - 1; i >= 0; i--)
        answer += ((trit[i] - '0') * pow(3, trit.length() - i - 1));
    return answer;
}
This post is licensed under CC BY 4.0 by the author.