C++ 中二进制表示中 0 和 1 的异或计数
本题给定一个数字。我们的任务是找出该数字在二进制表示中 0 和 1 次数的异或值。
我们举一个例子来理解这个问题,
输入
n = 9
输出
0
解释
binary = 1001 Count of 0s = 2 Count of 1s = 2 2 ^ 2 = 0
为了解决这个问题,我们将首先将数字转换为其二进制等价,然后遍历数字的每个二进制位,计算 0 和 1 的次数,然后再找出 0 和 1 的次数的异或值。
以下示例程序演示了上述解决方案,
示例
#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<<"XOR of count of 0s and 1s in binary of "<<n<<" is "<<countXOR10(n);
return 0;
}输出
XOR of count of 0s and 1s in binary of 21 is 1
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP