Programmers - 3진법 뒤집기

이준희·2022년 7월 12일

Algorithm

목록 보기
9/16

Programmers - 3진법 뒤집기

3진법으로 만든 숫자를 뒤집어서, 다시 10진수로 만드는 간단한 문제였다.

#include <string>
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

int solution(int n) {
    int answer = 0, temp;
    string ternary;
    while(n != 0){
        temp = n % 3;
        ternary += (temp + '0');
        n /= 3;
    }
    reverse(ternary.begin(), ternary.end());
    int idx = 1;
    for(int i = 0; i < ternary.size(); i++){
        answer += (ternary[i] - '0') * idx;
        idx *= 3;
    }
    return answer;
    
}
profile
뉴비 개발자입니다!!

0개의 댓글