C++中計算按位異或結果為偶數的數對
給定一個整數陣列,任務是計算可以使用給定陣列值形成的所有數對的總數,使得對數對進行異或運算的結果為偶數。
異或運算的真值表如下所示
| A | B | A XOR B |
| 0 | 0 | 0 |
| 1 | 0 | 1 |
| 0 | 1 | 1 |
| 1 | 1 | 0 |
輸入 − int arr[] = {2, 8, 1, 5, 11}
輸出 − 按位異或結果為偶數的數對個數為 − 4
解釋 −
| a1 | a2 | a1 XOR a2 |
| 2 | 8 | 10 |
| 2 | 1 | 3 |
| 2 | 5 | 7 |
| 2 | 11 | 9 |
| 8 | 1 | 9 |
| 8 | 5 | 13 |
| 8 | 11 | 3 |
| 1 | 5 | 4 |
| 1 | 11 | 10 |
| 5 | 11 | 14 |
下面程式中使用的方法如下:
輸入一個整數元素陣列來形成數對
計算陣列的大小,並將資料傳遞給函式以進行進一步處理。
建立一個臨時變數count來儲存以異或運算結果為偶數形成的數對。
從i=0開始迴圈到陣列的大小
在迴圈內,如果arr[i] % 2 == 0,則將count加1
將temp設定為size * (size - 1)
設定另一個臨時變數pairs = temp / 2
現在計算陣列中奇數對的數量為count * (size - count)
現在計算偶數對的數量為總對數 - 奇數對數
返回偶數對的數量
列印結果。
示例
#include <iostream>
using namespace std;
//Count pairs with Bitwise XOR as EVEN number
int XOR_Even(int arr[], int size){
int count = 0;
for (int i = 0; i < size; i++){
if (arr[i] % 2 != 0){
count++;
}
}
int temp = size * (size-1);
int Pairs = temp / 2;
int odd = count * (size - count);
int even = Pairs - odd;
return even;
}
int main(){
int arr[] = { 2, 6, 1, 8};
int size = sizeof(arr) / sizeof(arr[0]);
cout<<"Count of pairs with Bitwise XOR as EVEN number are: "<<XOR_Even(arr, size);
return 0;
}輸出
如果我們執行以上程式碼,它將生成以下輸出:
Count of pairs with Bitwise XOR as EVEN number are: 3
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP