位运算模板

位运算模板

1. n >> k 移位

常见问题:n 的二进制表示中的第 k 位是几?

例子:

int a =(8>>2)&1 ;
int b = (8>>3)&1;
cout<<a<<endl;
cout<<b<<endl;

输出:

0
1

 

2. lowbit(x)

lowbit(x)操作:返回x的二进制表示的最后一位1。

因为 -x 在计算机以补码存储为 -x = ~x + 1,则 x & -x = x & ( ~x + 1)

问题-求二进制数中1的个数

普通法

int BitCount(unsigned int n)
{
    unsigned int c =0 ; // 计数器
    while (n >0)
    {
        if((n &1) ==1) // 当前位是1
            ++c ; // 计数器加1
        n >>=1 ; // 移位
    }
    return c ;
}

简化:

int BitCount1(unsigned int n)
{
    unsigned int c =0 ; // 计数器
    for (c =0; n; n >>=1) // 循环移位
        c += n &1 ; // 如果当前位是1,则计数器加1
    return c ;
}

例子:

代码:

int getbitscount(int x){
    int ans=0;
    while (x)
    {
        ans++;
        x-=(x&-x);
    }
    return ans;
}
int  main(){
    int n;
    cin>>n;
    int *arr = new int[n+1];
    for (int i = 0; i < n; i++)
    {
        cin>>arr[i];
        cout<<getbitscount(arr[i])<<" ";
    }
}

3. n &= n - 1

n &= n - 1 操作,消除 n 的二进制表示的最后一位1.

 例题:

代码:

int getbitscount(int x){
    int ans=0;
    while (x)
    {
        ans++;
        x=x&(x-1);
    }
    return ans;
}
int  main(){
    int n;
    cin>>n;
    int *arr = new int[n+1];
    for (int i = 0; i < n; i++)
    {
        cin>>arr[i];
        cout<<getbitscount(arr[i])<<" ";
    }
}

4.C++ 位运算函数

__builtin_parity(n)

该函数是判断n的二进制中1的个数的奇偶性

int n = 15;                     //二进制为1111
int m = 7;                      //二进制为111
cout<<__builtin_parity(n)<<endl;//偶数个1,输出0
cout<<__builtin_parity(m)<<endl;//奇数个1,输出1

__builtin_popcount(n)

该函数时判断n的二进制中有多少个1

int n = 15;                       //二进制为1111
cout<<__builtin_popcount(n)<<endl;//输出结果为4

__builtin_ctz(n)

该函数判断n的二进制末尾后面0的个数,n=0时结果未定义
int n = 1;                      //二进制为1
int m = 8;                      //二进制为1000
cout<<__builtin_ctzll(n)<<endl; //输出0
cout<<__builtin_ctz(m)<<endl;   //输出3

__builtin_clz(n)

n前导0的个数, n=0时结果未定义

long long n = 1;                //二进制为000....001 64位整数
int m = 8;                      //二进制为000...1000 32位整数
cout<<__builtin_clzll(n)<<endl; //输出63
cout<<__builtin_clz(m)<<endl;   //输出28

__builtin_ffs(n)

该函数判断n的二进制末尾最后一个1的位置,从1开始

int n = 1;                  //二进制为1
int m = 8;                  //二进制为1000
cout<<__builtin_ffs(n)<<endl;//输出1
cout<<__builtin_ffs(m)<<endl;//输出4

因上求缘,果上努力~~~~ 作者:每天卷学习,转载请注明原文链接:https://www.cnblogs.com/BlairGrowing/p/13908558.html

原文地址:https://www.cnblogs.com/BlairGrowing/p/13908558.html