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