[프로그래머스 Lv1] 비밀지도

수민이슈·2023년 3월 16일
0

[C++] 코딩테스트

목록 보기
8/116
post-thumbnail

🖊️ 문제

https://school.programmers.co.kr/learn/courses/30/lessons/17681

🖊️ 풀이

문제 보자마자 거침없이 풀었는데..
바로 통과했는데..
근데 뭔가 이상했따
너무 비효율적인 느낌?
굳이 이걸 싹 다 2진수로 바꾸고 그걸 다 비교한다고?
그래서 일단 통과시키고 다른 사람들의 코드를 봤는데
와 OR 연산자
생각도 못했따...
역시 다른 사람들의 코드를 봐야 한다.

OR 연산자 |
0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1

이런..
밥오

🖊️ 코드

내가 푼 코드

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

// 공백 공백 = 공백
// 공백 벽 = 벽
// 벽 벽 = 벽

vector<int> GetBinary(int n, int num) {
    vector<int> binary;
    
    while(num > 1) {
        binary.emplace_back(num % 2);
        num /= 2;
    }
    binary.emplace_back(num);
    
    while(binary.size() != n) {
        binary.emplace_back(0);
    }
    
    reverse(binary.begin(), binary.end());
    return binary;
    
}

vector<string> solution(int n, vector<int> arr1, vector<int> arr2) {
    vector<string> answer;
    
    for (int j = 0 ; j < n ; j++) {
        string line = "";
        vector<int> a = GetBinary(n, arr1[j]);
        vector<int> b = GetBinary(n, arr2[j]);

        for (int k = 0 ; k < n ; k++) {
            string space = (a[k] == 0 && b[k] == 0 ? " " : "#");
            line += space;
        }
        answer.emplace_back(line);
    }
    return answer;
}

내가 푼 방식은..
받아내서 싹 다 2진수로 바꾸고 그 벡터들을 싹 다 비교하는거다.
지금은 주어진 범위도 적어서 걍 통과한 것 같은데
말이 안된다 이런 주먹구구식..

OR 연산자를 이용한 코드 (참고)

#include <string>
#include <vector>

using namespace std;

vector<string> solution(int n, vector<int> arr1, vector<int> arr2) {
    vector<string> answer;
    
    for (int i = 0 ; i < n ; i++) {
        arr1[i] = arr1[i] | arr2[i];        // arr1과 arr2의 비트연산한 값이 나옴
        string line;
        
        while(line.length() != n) {
            if (arr1[i] % 2 == 0) line = " " + line;
            else line = "#" + line;
            arr1[i] /= 2;
        }
        
        
        answer.emplace_back(line);
    }
    
    return answer;
}

이게 말이 되나
걍 메모리는 조금 더 썼는데
시간은 단축됐다

진짜 알고리즘의 세계는...어렵구나

0개의 댓글