Tricks

二进制/位运算相关

内建函数

  • __builtin_ctzll(x)xx 左侧连续 00 的个数

  • __builtin_popcount(x)xx 二进制表示中 11 的个数

Lowbit

  • x&-x 求左侧一个 11,如 (10100)2(100)2(10100)_2\to(100)_2

  • 使用 Lowbit 预处理状压中二进制数对应数组元素的和值

    1
    2
    3
    for(int s=1;s<(1<<n);s++){
    sum[s]=sum[s^(s&-s)]+a[__builtin_ctzll(s&-s)+1];
    }
  • 使用 Lowbit 枚举二进制数中每一个 11

    1
    2
    3
    for(int t=x;t;t-=t&-t){
    //此时用t&-t从左到右取出所有1
    }

Tricks
https://shicj.pages.dev/2026/06/25/Tricks/
作者
shicj
发布于
2026年6月25日
许可协议