Algorithm/C++ - 프로그래머스

프로그래머스 - 3진법 뒤집기

ㅇㅇ잉 2021. 2. 17. 02:15

3진법 뒤집기.

그냥..시키는 대로 순서대로 하면 된다.

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
#include <string>
#include <vector>
#include <iostream>
using namespace std;
 
int solution(int n) {
    int answer = 0;
    
    vector <int> v;
    
    while(n!=0){
        v.push_back(n%3);
        n/=3;
    }
    
    int power=3;
    
    for(int i=v.size()-1;i>=0;i--){
        if(i==v.size()-1) {answer+=v[i]; continue;}
        answer += v[i]*power;
        power*=3;
    }
    
    return answer;
}
cs

 

근데 풀고 나서 다른 사람의 풀이를 보니, 쫌 바보같은 짓을 했다.

vector를 써놓고 제대로 활용하지 못한 느낌..?

while문을 돌리면서 v.empty()확인하면서,

굳이 index를 쓰지 않고도 풀 수 있다.

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
#include <string>
#include <vector>
#include <iostream>
using namespace std;
 
int solution(int n) {
    int answer = 0;
    
    vector <int> v;
    
    while(n!=0){
        v.push_back(n%3);
        n/=3;
    }
    
    int power=1;
    
    while(!v.empty()){
        answer += v.back()*power;
        v.pop_back();
        power*=3;
    }
    
    return answer;
}
cs

이렇게 보니까 코드가 한결 깔끔하다.