본문 바로가기

코딩테스트 대비

[프로그래머스 Lv.1] 3진법 뒤집기

문제 설명

문제 해설

1. n을 3진법으로 만드는 과정에서 뒤집은 값을 v에 저장

   n%3값을 저장

ex ) 45%3=0, 45/3=15

     15%3=0, 15/3=5

     5%3=2, 5/3=1

     1%3=1, 1/3=0

     3진수 n 1200

     뒤집은 3진수 n(new_n)은 0021

     배열에 저장 v.push_back(n%3);

     while(n>0){
           v.push_back(n%3);
           n=n/3;      

     }

3. 뒤집은 new 10진수로 만들기

  • pow(제곱할 수, 승수)를 아는지가 가장 중요한 포인터였던것 같다 ㅠㅅㅠ (난 몰랐음)

   sqrt랑 세트로 알아두기!!!!

#include <string>
#include <cmath>
#include <iostream>
#include <vector>

using namespace std;

int solution(int n) {
    int answer = 0;
    int cnt=0;
    vector<int> v;
    
    while(n>0){
        v.push_back(n%3);
        n=n/3;
        cnt++;
    }
    cout <<cnt<<'\n';
    for(int i=0; i<cnt; i++){
        answer=answer+v[cnt-1-i]*pow(3,i);
    }
    
    return answer;
}