[c++/알고리즘] 프로그래머스 3진법뒤집기

corncheese·2021년 8월 12일
0

알고리즘문제풀이

목록 보기
27/31

10진수로 다시 변환하기 위해 pow함수도 쓰고.. 아둥바둥 했으나..
매우 간단한 풀이가 있었다..
머리 좀 잘쓰자..

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

using namespace std;

int solution(int n) {
    int answer = 0;
    int j=0;
    vector<int> t;
    
    while(n!=0){
        t.push_back(n%3);
        n = n/3;
    }
    
    for(int i=t.size()-1; i>=0; i--){
        double x=0;
        x = pow(3, i);
        answer += t[j]*x;
        j++;
    }
    return answer;
}

참고한 풀이

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

using namespace std;

int solution(int n) {
    int answer = 0;
    int j=1;
    vector<int> t;
    
    while(n!=0){
        t.push_back(n%3);
        n = n/3;
    }
    
    while(!t.empty()){
        answer += j * t.back();
        t.pop_back();
        j *= 3;
    }
    return answer;
}

0개의 댓글