How do I count the number of zero bits in an integer?

前端 未结 12 2122
梦谈多话
梦谈多话 2021-02-02 00:25

How would i go about finding the number of \'zero\' bits in C++. Suppose I have an integer;

int value = 276; 

For which I have the bits 100010

12条回答
  •  故里飘歌
    2021-02-02 00:56

    #include 
    using namespace std;
    #define ll long long int
    
    
    int main() {
        ll a;
        cin>>a;
        ll ones=__builtin_popcountll(~a);
        ll zero=__builtin_clzll(a);
        ll num=abs(ones-zero);
        cout<

    with the help of builtin gcc functions i.e. popcount(counts number of set bit) and clz(count number of leading zero's) we can calculate the number of zero bit in an integer

    you can read about them here https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html, https://www.geeksforgeeks.org/builtin-functions-gcc-compiler/

提交回复
热议问题