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

꿈별·2024년 1월 16일
0

문제풀이

목록 보기
37/52

문제


풀이

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

#include <iostream>

using namespace std;

int solution(int n) {
    int mod, ten=0;
    vector<int> three;

    while (0 < n)
    {
        mod = n % 3;
        n /= 3;
        three.push_back(mod);
    }

    for (int i = 0 ; i < three.size(); i++)
    {
        ten += (pow(3, three.size() - i - 1) * (three[i]));
    }
    return ten;
}  

  • 예제
    • 123(10)을 3진수로 변환하기
    • 몫 / 나눠지는 수 ... 나머지
      3 / 123 ... 0
      3 / 41 ... 2
      3 / 13 ... 1
      3 / 4 ... 1
      3 / 1 ... 1
      -> 11120(3)
    • 뒤집으면 02111
    • 10진수로 변환하면
      3^4 * 0 + 3^3 * 2 + 3^2 * 1 + 3^1 * 1 + 3^0 * 1
      = 0 + 54 + 9 + 3 + 1
      = 67(10) << 답

결과


pow()

거듭제곱 함수

// 헤더
#include <cmath>
// 함수 원형
pow(n, x)

-> n의 x승으로 거듭제곱한다.

0개의 댓글