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

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


Contents



문제


문제를 보시려면 링크를 클릭해주세요.


풀이


주어진 숫자 n을 앞뒤로 뒤집은 3진법 상의 수로 받아 문자열에 담아줍니다.

문자열에 담긴 값을 다시 10진법의 수로 변환해줍니다.

이 때, cmath 헤더에 있는 pow 함수를 사용해 n 제곱을 구할 수 있습니다.

ex) \(pow(3,2) = 3의 2제곱 = 3^2 = 9\)


소스 코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <string>
#include <cmath>

using namespace std;

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



This post is licensed under CC BY 4.0 by the author.

[프로그래머스] 같은 숫자는 싫어 / C++

[프로그래머스] 소수 찾기 / C++

Comments powered by Disqus.