[백준] 11723번 집합(c++)

1808 단어 백준백준

[백준] 11723번 집합

문제 링크: https://www.acmicpc.net/problem/11723

문제 및 입출력

문제 접근

비트마스크로 푸는 문제이다.
21비트를 사용하여, 1~20까지의 숫자가 들어있으면 해당 숫자에 맞는 비트를 1로 바꾸었고, 아니면 0으로 두었다.

add or연산자를 사용하여 구현
remove not과 and연산자를 사용하여 구현
check and연산자 구현
toggle xor연산자로 구현

코드 구현(c++)

#include <iostream>

using namespace std;

int num = 0;
void add(int temp){
    num |= (1 << temp);
}
void remove(int temp){
    num &= ~(1 << temp);
}
bool check(int temp){
    if(num & (1 << temp)) return true;
    else return false;
}
void toggle(int temp){
    num ^= (1 << temp);
}
void all(){
    num = (1 << 21) - 1;
}
void empty(){
    num = 0;
}
int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);

    int testCase;
    cin >> testCase;
    string str;
    int temp;
    for(int i = 0 ; i < testCase ; i++){
        cin >> str;
        if(str == "add") {
            cin >> temp;
            add(temp);
        }
        else if(str == "remove") {
            cin >> temp;
            remove(temp);
        }
        else if(str == "check") {
            cin >> temp;
            if(check(temp)) cout << "1\n";
            else cout << "0\n";
        }
        else if(str == "toggle") {
            cin >> temp;
            toggle(temp);
        }
        else if(str == "all") all();
        else empty();
    }    

}

좋은 웹페이지 즐겨찾기