C++:: 프로그래머스 < [1차] 비밀지도 >

jahlee·2023년 7월 16일
0

프로그래머스_Lv.1

목록 보기
44/75
post-thumbnail

주어진 숫자 배열들을 이진수로 변환후 0 은 ' ', 1은 '#'으로 변환하여 두 배열을 합쳐주면 되는 문제이다. or연산이라 생각하면 편하다. 해당 문제는 or연산으로 풀 수 있지만 아래 코드는 그냥 직관적으로 풀었다.

#include <string>
#include <vector>
#include <bitset>
using namespace std;

void decodeNum(int n, vector<string>& map, vector<int>& arr) {
    for (int i=0; i<n; i++) {
        string decoded = bitset<16>(arr[i]).to_string().substr(16-n);// 숫자를 2진수로 변환하고 크기에 맞게 잘라준다.
        for (int j=0; j<n; j++) {
            if (decoded[j] == '1') map[i][j] = '#';// '1'이면 #을 찍어준다.
        }
    }
}

vector<string> solution(int n, vector<int> arr1, vector<int> arr2) {
    vector<string> answer(n, string(n, ' '));
    decodeNum(n, answer, arr1);
    decodeNum(n, answer, arr2);
    return answer;
}

or 연산을 활용한 풀이도 올려본다. 크게 다르지 않다.

#include <string>
#include <vector>
#include <bitset>
using namespace std;

vector<string> solution(int n, vector<int> arr1, vector<int> arr2) {
    vector<string> answer(n, string(n, ' '));
    for(int i=0;i<n;i++) arr1[i] = arr1[i]|arr2[i];
    for (int i=0; i<n; i++) {
        string decoded = bitset<16>(arr1[i]).to_string().substr(16-n);
        for (int j=0; j<n; j++) {
            if (decoded[j] == '1') answer[i][j] = '#';
        }
    }
    return answer;
}

0개의 댓글