Home Some Tricks
Post
Cancel

Some Tricks

快读函数

写一个「快速读入」函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
inline int read() {
    int x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

__builtin_clz 的用法

一个快捷取对数的方法: int logn = 31 - __builtin_clz(n);

int __builtin_clz (unsigned int x) 返回 x 前导 0 的个数, 如果 x=0 的话, 结果未知 (不过我的机器上是 31).

nint 类型, 长度是 32 位. 而对于 n 而言, 它的对数不过是它的二进制表示的位数减一. 例如 8 的二进制形式是 1000, 位数为 4, 它的对数是 3.

具体用法如下:

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
35
36
#include <iostream>
#include <cstdio>
using namespace std;
int clz(unsigned int x){
    return __builtin_clz(x);
}
int main() {
    unsigned int a;
    a=0;
    printf("0x%x ret=%d\n",a,clz(a));
    a=1;
    printf("0x%x ret=%d\n",a,clz(a));
    a=2;
    printf("0x%x ret=%d\n",a,clz(a));
    a=4;
    printf("0x%x ret=%d\n",a,clz(a));
    a=8;
    printf("0x%x ret=%d\n",a,clz(a));
    a=16;
    printf("0x%x ret=%d\n",a,clz(a));
    a=0xffff;
    printf("0x%x ret=%d\n",a,clz(a));
    a=0xfffffff;
    printf("0x%x ret=%d\n",a,clz(a));
    a=0x1fffffff;
    printf("0x%x ret=%d\n",a,clz(a));
    a=0x1fffffff;
    printf("0x%x ret=%d\n",a,clz(a));
    a=0x2fffffff;
    printf("0x%x ret=%d\n",a,clz(a));
    a=0x8fffffff;
    printf("0x%x ret=%d\n",a,clz(a));
    a=0xffffffff;
    printf("0x%x ret=%d\n",a,clz(a));
    return 0;
}
This post is licensed under CC BY 4.0 by the author.