C++中計算異或結果為奇數的數對


給定一個整數陣列,任務是計算可以使用給定陣列值形成的數對總數,使得對數對進行異或運算的結果為奇數。

異或運算的真值表如下所示

ABA XOR B
000
101
011
110

輸入 − int arr[] = {2, 8, 1, 5, 11}

輸出 − 異或結果為奇數的數對個數為 − 6

解釋

a1a2a1 XOR a2
2810
213
257
2119
819
8513
8113
154
11110
51114

下面程式中使用的演算法如下:

  • 輸入一個整數元素陣列以形成數對

  • 計算陣列大小,並將資料傳遞給函式進行進一步處理

  • 建立一個臨時變數 count 來儲存異或運算結果為奇數的數對。

  • 從 i = 0 開始迴圈到陣列大小

  • 在迴圈內部,如果 arr[i] % 2 == FALSE,則將 even_XOR 加 1,否則將 odd_XOR 加 1。

  • 現在將 count 設定為 odd_XOR * even_XOR

  • 返回 count

  • 列印結果

示例

 線上演示

#include <iostream>
using namespace std;
//Count pairs with Odd XOR
int Odd_XOR(int arr[], int size){
   int count = 0;
   int odd_XOR = 0;
   int even_XOR = 0;
   for (int i = 0; i < size; i++){
      if (arr[i] % 2 == 0){
         even_XOR++;
      }
      else{
         odd_XOR++;
      }
   }
   count = odd_XOR * even_XOR;
   return count;
}
int main(){
   int arr[] = { 2, 6, 1, 4 };
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Count of pairs with Odd XOR are: "<<Odd_XOR(arr, size);
   return 0;
}

輸出

如果執行以上程式碼,將生成以下輸出:

Count of pairs with Odd XOR are: 3

更新於:2020年8月31日

瀏覽量 155

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.