C ++中二进制表示形式的0和1的XOR计数

在这个问题上,我们得到了一个数字。我们的任务是在数字的二进制表示形式中找到0和1计数的XOR。

让我们举个例子来了解这个问题,

输入项

n = 9

输出结果

0

说明

binary = 1001

Count of 0s = 2

Count of 1s = 2

2 ^ 2 = 0

为了解决此问题,我们将首先转换其二进制等效项的数量,然后遍历该数量的每一位,计数0和1,然后找到计数0和计数1的XOR。

用于说明上述解决方案的程序,

示例

#include<iostream>

using namespace std;

int countXOR10(int n) {

   int count0s = 0, count1s = 0;

   while (n){

      (n % 2 == 0) ? count0s++ :count1s++;

      n /= 2;

   }

   return (count0s ^ count1s);

}

int main() {

   int n = 21;

   cout<<"二进制的0和1计数的XOR "<<n<<" 是 "<<countXOR10(n);

   return 0;

}

输出结果

二进制的0和1计数的XOR 21 是 1

以上是 C ++中二进制表示形式的0和1的XOR计数 的全部内容, 来源链接: utcz.com/z/315936.html

回到顶部