비트마스크를 사용하는 문제입니다.
16진수로 0x00000을 기본값으로 받습니다.
16진수 5개이므로
0000 0000 0000 0000 0000
20개의 비트를 표현 가능합니다.
add - or연산자로 해당 비트를 참으로 만듭니다.
remove - 0xFFFFF - 해당 비트를 and연산을 통해 처리합니다.
check - and 연산자를 통해 확인합니다.
toggle - xor 연산자를 이용해 확인합니다.
all - (bit = 0xFFFFF)
empty - (bit = 0x00000)
* <<, >> 시프트 연산으로 해당 방향으로 비트를 밀어줍니다.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int bit = 0x00000;
void add(int x)
{
bit = bit | (1 << x);
}
void remove(int x)
{
bit = bit & (0xFFFFF - (1 << x));
}
void check(int x)
{
int num;
bit &(1 << x) ? num = 1 : num = 0;
cout << num << "\n";
}
void toggle(int x)
{
bit = bit ^ (1 << x);
}
void all()
{
bit = 0xFFFFF;
}
void empty()
{
bit = 0x00000;
}
int main(int argc, char *argv[])
{
ios_base ::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
int num;
string str;
cin >> n;
while (n--)
{
cin >> str;
if (str != "all" && str != "empty")
{
cin >> num;
--num;
}
if (str == "add")
{
add(num);
}
else if (str == "remove")
{
remove(num);
}
else if (str == "check")
{
check(num);
}
else if (str == "toggle")
{
toggle(num);
}
else if (str == "all")
{
all();
}
else if (str == "empty")
{
empty();
}
}
return 0;
}
'알고리즘' 카테고리의 다른 글
[C++] 백준 2234번 성곽 (0) | 2021.03.22 |
---|---|
[C++] 백준 1062번 가르침 (0) | 2021.03.14 |
[C++] 프로그래머스 - 실패율 (0) | 2021.03.10 |
[C++] 프로그래머스 - 블록 이동하기 (0) | 2021.03.08 |
[C++] 프로그래머스 - 외벽 점검 (0) | 2021.03.03 |