[C++] 3진법 뒤집기 - 구현

wansuper·2023년 12월 28일
0

CodingTest

목록 보기
19/34

내 풀이

#include <string>
#include <iostream>
#include <vector>
#include <math.h>

using namespace std;

// 비트 수 구하기
int bit_num(int a) {
    int bit = 0;
    for (int i = a; i > 0;) {
        i /= 3;
        bit++;
    }
    cout << "bit 수는 " << bit << endl;
    return bit;
}

int solution(int n) {
    int answer = 0;
    int bit = bit_num(n);
    
    // bit 수 만큼의 크기를 가진 배열 초기화
    int arr_3div[bit];
    
    // 연산된 3진법이 각 배열에 원소로 삽입
    for (int i = bit - 1; i >= 0; i--) {
        
        arr_3div[i] = n % 3;
        n = n / 3;
    }
    
    // 디버깅
    for (int i = 0; i < bit; i++) {
        cout << arr_3div[i] << " ";
    }
    cout << endl;
    
    // 정답 도출
    for (int i = 0; i < bit; i++) {
        
        answer += (pow(3, i) * arr_3div[i]);
    }
    cout << "answer : " << answer;
    
    return answer;
}

int main() {
    solution(45);
    // solution(125);

}
profile
🚗 Autonomous Vehicle 🖥️ Study Alone

0개의 댓글