Bitmask (2), "자주 사용되는 형태"
본문 바로가기
C, C++/Data structure

Bitmask (2), "자주 사용되는 형태"

by 조훈이 2021. 2. 25.

Bitmask (2), "자주 사용되는 형태"


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
int nth_bit_on(int n) {
    return 1 << n;
// n'th bit 켜기
 
bool is_nth_bit_on(int num, int n) {
    if (num & (1 << n))
        return true;
    else
        return false;
// n'th bit 켜져있는지 확인
 
int on_all_bit_upto_n(int n) {
    return (1 << n) - 1;
// n'th bit 까지 모두 켜기
 
bool is_power_of_2(int num) {
    return (num & (num - 1)) == 0;
// num 이 2^n인지 판단.
// 2^n 이면 num(2) 10..00(2) 의 형태이므로!
 
int count_bit(int num) {
    int count, k;
    count = k = 0;
 
    // num(2) 보다 (1 << k)가 작으면 계속 돈다.
    while (num >= (1 << k)) {
        // 만약 num 의 k'th bit 가 켜져있으면!
        if (num & (1 << k))
            count++;
        k++;
    }
 
    return count;
}
cs

 

728x90

'C, C++ > Data structure' 카테고리의 다른 글

이진 트리 (Binary Tree)  (0) 2023.01.14
세그먼트 트리 (Segment tree)  (0) 2021.08.03
힙[Heap], 삽입 및 삭제  (1) 2021.07.22
힙 [Heap], 최대힙/최소힙  (0) 2021.07.21
Bitmask (1), "Bit operator"  (0) 2021.02.09

댓글