본문 바로가기

코딩 테스트/프로그래머스

[Level 1, C++] 3진법 뒤집기

728x90
반응형

파이썬에는 진법 계산하는 함수같은게 있던데 c++엔 그런게 없다. 그래서 그냥 직접 진법 계산하는걸로 만들었다.

직접 계산하면 앞뒤로 뒤집을 필요없으니 좋았다.


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

int solution(int n) {
    int answer = 0;
    string str = "";
    int i = 0;
    while (true) {
        str.append(to_string(n % 3));
        n = n / 3;
        if( n == 0) break;
    }
    for (int i = 0; i < str.length(); i++) {
        cout << str[str.length() - i - 1] << endl;
        answer += (str[str.length() - i - 1] - 48) * pow(3, i);
    }
    return answer;
}

 

728x90
반응형