프로그래머스

[프로그래머스 C++] 3진법 뒤집기

민봉이 2022. 10. 23. 23:13
반응형

링크

https://school.programmers.co.kr/learn/courses/30/lessons/68935?language=cpp 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제 설명 및 제한 조건

나의 코드 

#include <string>
#include <vector>

using namespace std;

int solution(int n) {
    int answer = 0;
    vector<int> TernaryScale; 
    int Decimal = n;
    while(Decimal)
    {
        TernaryScale.push_back(Decimal % 3);
        Decimal /= 3;
    }
    int temp = 1;
    for(int i = TernaryScale.size() - 1; i >= 0; i--)
    {
        answer += TernaryScale[i] * temp;
        temp *= 3;
    }
    return answer;
}

채점 결과

다수 코드

#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <iostream>
using namespace std;

int solution(int n) {
    int answer = 0;
    vector<int> v;

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

    reverse(v.begin(), v.end());

    for(int i = 0; i < v.size(); i++)
        answer += pow(3, i) * v[i];

    return answer;
}

 

반응형