알고리즘/C++
[C++] 프로그래머스 비밀지도 (비트연산자)
지휘리릭
2020. 2. 28. 19:39
내가 처음 풀어본 방법
#include <string>
#include <vector>
using namespace std;
vector<string> solution(int n, vector<int> arr1, vector<int> arr2) {
vector<string> answer;
// 2진수 저장할 배열
string temp1 = string(n, '0');
string temp2 = string(n, '0');
string temp3 = string(n, '0');
int num, i, j, pos = 1;
for (i = 0; i < n; i++) {
temp1 = temp2 = temp3 = string(n, ' ');
pos = 1;
num = arr1[i];
while (num > 0) {
if (num % 2 == 0) temp1[n - pos] = ' ';
if (num % 2 == 1) temp1[n - pos] = '#';
num = num / 2;
pos++;
}
pos = 1;
num = arr2[i];
while (num > 0) {
if (num % 2 == 0) temp2[n - pos] = ' ';
else temp2[n - pos] = '#';
num = num / 2;
pos++;
}
for (j = 0; j < n; j++) {
if (temp1[j] == ' ' && temp2[j] == ' ') { temp3[j] = ' '; }
else temp3[j] = '#';
}
answer.push_back(temp3);
}
return answer;
}
다른 사람들의 풀이
#include <string>
#include <vector>
using namespace std;
vector<string> solution(int n, vector<int> arr1, vector<int> arr2) {
vector<string> answer;
string temp = "";
int i, j;
for(i =0; i < n; i++){
arr1[i] = arr1[i] | arr2[i];
temp = "";
for(j = 0; j < n; j++){
if(arr1[i]%2 ==0) temp = ' '+temp;
else temp = '#' + temp;
arr1[i] = arr1[i] >> 1;
}
answer.push_back(temp);
}
return answer;
}
진짜 사람들은 대단한 것 같다. 난 아주 구구절절 난리 부르스를 했는데 이렇게나 간단하다니..
arr1, arr2 의 값을 각각 2진수로 바꾸고나서 OR 연산을 펼치는 것이 아니라
arr1, arr2 를 바로 OR 연산 시키고 2진수로 바꾼다. OR 연산은 2진수에서만 펼치는 줄 알았다.
그 다음에 혹시 값이 작으면 2진수 시켰을 때, 그냥 00010(2) 이렇게 되는 것이 아니라 10(2) 이렇게 된다.
이러한 것을 처리해주기 위해서 for문으로 그만큼 돌리게 했다. 신기하다.
나도 나중에 이런 풀이법을 생각할 수 있었으면 좋겠다.