C/C++ 程式用於查詢給定正整數陣列中出現奇數次的數字。此陣列中所有數字都出現偶數次。


此 C++ 程式用於在給定的正整數陣列中查找出現奇數次的數字。此陣列中所有數字都出現偶數次。

Input: arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7}
Output: 7

說明

使用兩個迴圈,其中外迴圈逐個遍歷所有元素,內迴圈統計外迴圈遍歷的元素出現的次數。

示例

#include <iostream>
using namespace std;
int Odd(int arr[], int n){
   for (int i = 0; i < n; i++) {
      int ctr = 0;
      for (int j = 0; j < n; j++) {
         if (arr[i] == arr[j])
            ctr++;
      }
      if (ctr % 2 != 0)
         return arr[i];
   }
   return -1;
}
int main() {
   int arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7};
   int n = 9;
   cout <<Odd(arr, n);
   return 0;
}

更新於: 20-Aug-2019

350 次瀏覽

開啟你的 事業

完成課程即可獲得認證

開始
廣告